From 5264a852306a5427f8a35d5dae2d15a94df43b4e Mon Sep 17 00:00:00 2001 From: Fabian Thomys Date: Thu, 1 Oct 2026 10:38:23 +0200 Subject: [PATCH 1/6] Add Basic Icinga Plugins --- Tests/ConvertTo-IcingaSortedArray.Tests.ps1 | 78 ++++ .../Get-IcingaDirectoryInformation.Tests.ps1 | 233 ++++++++++ Tests/Get-IcingaDiskInformation.Tests.ps1 | 179 ++++++++ Tests/Get-IcingaWindowsInformation.Tests.ps1 | 130 ++++++ Tests/IcingaServiceStartupType.Tests.ps1 | 83 ++++ Tests/IcingaServiceStatus.Tests.ps1 | 106 +++++ Tests/Invoke-IcingaCheckCPU.Tests.ps1 | 171 +++++++ Tests/Invoke-IcingaCheckDirectory.Tests.ps1 | 207 +++++++++ Tests/Invoke-IcingaCheckMemory.Tests.ps1 | 188 ++++++++ ...Invoke-IcingaCheckPartitionSpace.Tests.ps1 | 188 ++++++++ Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 | 194 ++++++++ Tests/Invoke-IcingaCheckService.Tests.ps1 | 212 +++++++++ Tests/Invoke-IcingaCheckUptime.Tests.ps1 | 108 +++++ Tests/Test-IcingaArrayFilter.Tests.ps1 | 58 +++ build/Build-ModuleProject.ps1 | 7 + .../DataTypes/IcingaServiceStartupType.ps1 | 107 +++++ src/Classes/DataTypes/IcingaServiceStatus.ps1 | 105 +++++ src/Classes/Tools/IcingaSortKey.ps1 | 169 +++++++ .../Private/Set-InternalExitCodes.ps1 | 111 +++++ src/Plugins/Public/Invoke-IcingaCheckCPU.ps1 | 217 +++++++++ .../Public/Invoke-IcingaCheckDirectory.ps1 | 335 ++++++++++++++ .../Public/Invoke-IcingaCheckMemory.ps1 | 242 ++++++++++ .../Invoke-IcingaCheckPartitionSpace.ps1 | 214 +++++++++ .../Public/Invoke-IcingaCheckPerfCounter.ps1 | 256 +++++++++++ .../Public/Invoke-IcingaCheckService.ps1 | 267 +++++++++++ .../Public/Invoke-IcingaCheckUptime.ps1 | 111 +++++ .../Disk/Public/Get-IcingaDiskInformation.ps1 | 303 ++++++++++++ .../Public/Get-IcingaDirectoryInformation.ps1 | 434 ++++++++++++++++++ .../Private/Test-ModuleWildcardMatch.ps1 | 44 ++ .../Public/ConvertTo-IcingaSortedArray.ps1 | 91 ++++ .../Public/Get-IcingaWindowsInformation.ps1 | 129 ++++++ src/Tools/Public/Test-IcingaArrayFilter.ps1 | 96 ++++ 32 files changed, 5373 insertions(+) create mode 100644 Tests/ConvertTo-IcingaSortedArray.Tests.ps1 create mode 100644 Tests/Get-IcingaDirectoryInformation.Tests.ps1 create mode 100644 Tests/Get-IcingaDiskInformation.Tests.ps1 create mode 100644 Tests/Get-IcingaWindowsInformation.Tests.ps1 create mode 100644 Tests/IcingaServiceStartupType.Tests.ps1 create mode 100644 Tests/IcingaServiceStatus.Tests.ps1 create mode 100644 Tests/Invoke-IcingaCheckCPU.Tests.ps1 create mode 100644 Tests/Invoke-IcingaCheckDirectory.Tests.ps1 create mode 100644 Tests/Invoke-IcingaCheckMemory.Tests.ps1 create mode 100644 Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 create mode 100644 Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 create mode 100644 Tests/Invoke-IcingaCheckService.Tests.ps1 create mode 100644 Tests/Invoke-IcingaCheckUptime.Tests.ps1 create mode 100644 Tests/Test-IcingaArrayFilter.Tests.ps1 create mode 100644 src/Classes/DataTypes/IcingaServiceStartupType.ps1 create mode 100644 src/Classes/DataTypes/IcingaServiceStatus.ps1 create mode 100644 src/Classes/Tools/IcingaSortKey.ps1 create mode 100644 src/Plugins/Public/Invoke-IcingaCheckCPU.ps1 create mode 100644 src/Plugins/Public/Invoke-IcingaCheckDirectory.ps1 create mode 100644 src/Plugins/Public/Invoke-IcingaCheckMemory.ps1 create mode 100644 src/Plugins/Public/Invoke-IcingaCheckPartitionSpace.ps1 create mode 100644 src/Plugins/Public/Invoke-IcingaCheckPerfCounter.ps1 create mode 100644 src/Plugins/Public/Invoke-IcingaCheckService.ps1 create mode 100644 src/Plugins/Public/Invoke-IcingaCheckUptime.ps1 create mode 100644 src/Provider/Disk/Public/Get-IcingaDiskInformation.ps1 create mode 100644 src/Provider/FileSystem/Public/Get-IcingaDirectoryInformation.ps1 create mode 100644 src/Tools/Private/Test-ModuleWildcardMatch.ps1 create mode 100644 src/Tools/Public/ConvertTo-IcingaSortedArray.ps1 create mode 100644 src/Tools/Public/Get-IcingaWindowsInformation.ps1 create mode 100644 src/Tools/Public/Test-IcingaArrayFilter.ps1 diff --git a/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 b/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 new file mode 100644 index 0000000..ed69f99 --- /dev/null +++ b/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 @@ -0,0 +1,78 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'ConvertTo-IcingaSortedArray' { + Context 'Natural order' { + It 'sorts processor instances numerically with the totals last' { + $Sorted = ConvertTo-IcingaSortedArray -InputObject @('0,10', '_Total', '1,0', '0,2', '0,_Total', '0,0'); + $Sorted | Should -Be @('0,0', '0,2', '0,10', '0,_Total', '1,0', '_Total'); + } + + It 'compares digit runs by value and text case-insensitively' { + $Sorted = ConvertTo-IcingaSortedArray -InputObject @('core 10', 'Core 9', 'CORE 1', 'Core 01a'); + $Sorted | Should -Be @('CORE 1', 'Core 01a', 'Core 9', 'core 10'); + } + + It 'compares numbers numerically and puts $null first' { + $Sorted = ConvertTo-IcingaSortedArray -InputObject @(10, 9, $null, 100); + $Sorted | Should -Be @($null, 9, 10, 100); + } + + It 'sorts in descending order' { + $Sorted = ConvertTo-IcingaSortedArray -InputObject @('b', 'c', 'a') -Descending; + $Sorted | Should -Be @('c', 'b', 'a'); + } + } + + Context 'Properties' { + It 'sorts objects and hashtables by a property' { + $Objects = @([PSCustomObject]@{ 'Name' = 'Spooler'; }, [PSCustomObject]@{ 'Name' = 'AppInfo'; }); + (ConvertTo-IcingaSortedArray -InputObject $Objects -Property 'Name').Name | Should -Be @('AppInfo', 'Spooler'); + + $Tables = @(@{ 'Name' = 'D:\'; }, @{ 'Name' = 'C:\'; }); + (ConvertTo-IcingaSortedArray -InputObject $Tables -Property 'Name') | ForEach-Object { $_['Name'] } | Should -Be @('C:\', 'D:\'); + } + + It 'breaks ties with the next property' { + $Partitions = @( + @{ 'Disk' = 1; 'Partition' = 1; }, + @{ 'Disk' = 0; 'Partition' = 2; }, + @{ 'Disk' = 0; 'Partition' = 1; } + ); + $Sorted = ConvertTo-IcingaSortedArray -InputObject $Partitions -Property 'Disk', 'Partition'; + ($Sorted | ForEach-Object { '{0}:{1}' -f $_['Disk'], $_['Partition'] }) | Should -Be @('0:1', '0:2', '1:1'); + } + + It 'keeps equal elements in input order' { + $Objects = @( + [PSCustomObject]@{ 'Key' = 'a'; 'Order' = 1; }, + [PSCustomObject]@{ 'Key' = 'b'; 'Order' = 2; }, + [PSCustomObject]@{ 'Key' = 'a'; 'Order' = 3; }, + [PSCustomObject]@{ 'Key' = 'a'; 'Order' = 4; } + ); + (ConvertTo-IcingaSortedArray -InputObject $Objects -Property 'Key').Order | Should -Be @(1, 3, 4, 2); + (ConvertTo-IcingaSortedArray -InputObject $Objects -Property 'Key' -Descending).Order | Should -Be @(2, 1, 3, 4); + } + } + + Context 'Result shape' { + It 'returns a new array and leaves the input unchanged' { + $Input1 = @('b', 'a'); + $Sorted = ConvertTo-IcingaSortedArray -InputObject $Input1; + $Sorted | Should -Be @('a', 'b'); + $Input1 | Should -Be @('b', 'a'); + } + + It 'returns an array for a single element and an empty array for no element' { + $Single = ConvertTo-IcingaSortedArray -InputObject @('a'); + ($Single -is [array]) | Should -BeTrue; + $Single.Count | Should -Be 1; + + $Empty = ConvertTo-IcingaSortedArray -InputObject @(); + ($Empty -is [array]) | Should -BeTrue; + $Empty.Count | Should -Be 0; + } + } +} diff --git a/Tests/Get-IcingaDirectoryInformation.Tests.ps1 b/Tests/Get-IcingaDirectoryInformation.Tests.ps1 new file mode 100644 index 0000000..da838ed --- /dev/null +++ b/Tests/Get-IcingaDirectoryInformation.Tests.ps1 @@ -0,0 +1,233 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Get-IcingaDirectoryInformation' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + # Writes a file of the given size and sets its time stamps. + function New-TestFile() + { + param ( + [string]$Path = '', + [int]$Size = 0, + [datetime]$LastWrite = [datetime]::Now, + [datetime]$Creation = [datetime]::Now, + [datetime]$LastAccess = [datetime]::Now, + [switch]$Hidden = $false + ); + + [System.IO.File]::WriteAllBytes($Path, [byte[]]::new($Size)); + [System.IO.File]::SetCreationTime($Path, $Creation); + [System.IO.File]::SetLastWriteTime($Path, $LastWrite); + [System.IO.File]::SetLastAccessTime($Path, $LastAccess); + + if ($Hidden) { + [System.IO.File]::SetAttributes($Path, [System.IO.FileAttributes]::Hidden); + } + } + + # Calls the provider inside the module scope, where IcingaError is visible. + function Invoke-TestDirectory() + { + param ( + [hashtable]$Arguments = @{ } + ); + + return (& $script:IcingaModule { + param ($Arguments); + + Get-IcingaDirectoryInformation @Arguments; + } $Arguments); + } + + # Layout (sizes in bytes, ages relative to now): + # a.log 100 (written at noon 10 days ago), b.log 2000 (1h), c.txt 50 (40d, + # created 40d ago, last access 40d ago), hidden.log 10 (hidden), + # sub\ (written 3d ago) with d.log 5000 (2d) and deep\e.log 1 (now), + # hidden\ (hidden folder) with f.log 7. + [datetime]$Now = [datetime]::Now; + $script:Root = Join-Path -Path $TestDrive -ChildPath 'scan'; + [string]$Sub = Join-Path -Path $script:Root -ChildPath 'sub'; + [string]$Deep = Join-Path -Path $Sub -ChildPath 'deep'; + [string]$Secret = Join-Path -Path $script:Root -ChildPath 'hidden'; + + New-Item -Path $Deep -ItemType Directory -Force | Out-Null; + New-Item -Path $Secret -ItemType Directory -Force | Out-Null; + + New-TestFile -Path (Join-Path -Path $script:Root -ChildPath 'a.log') -Size 100 -LastWrite $Now.AddDays(-10).Date.AddHours(12); + New-TestFile -Path (Join-Path -Path $script:Root -ChildPath 'b.log') -Size 2000 -LastWrite $Now.AddHours(-1); + New-TestFile -Path (Join-Path -Path $script:Root -ChildPath 'c.txt') -Size 50 -LastWrite $Now.AddDays(-40) -Creation $Now.AddDays(-40) -LastAccess $Now.AddDays(-40); + New-TestFile -Path (Join-Path -Path $script:Root -ChildPath 'hidden.log') -Size 10 -Hidden; + New-TestFile -Path (Join-Path -Path $Sub -ChildPath 'd.log') -Size 5000 -LastWrite $Now.AddDays(-2); + New-TestFile -Path (Join-Path -Path $Deep -ChildPath 'e.log') -Size 1; + New-TestFile -Path (Join-Path -Path $Secret -ChildPath 'f.log') -Size 7; + + [System.IO.Directory]::SetLastWriteTime($Sub, $Now.AddDays(-3)); + [System.IO.Directory]::SetLastWriteTime($Deep, $Now.AddDays(-3)); + $SecretInfo = [System.IO.DirectoryInfo]::new($Secret); + $SecretInfo.Attributes = $SecretInfo.Attributes -bor [System.IO.FileAttributes]::Hidden; + } + + It 'collects the statistics of the top level and skips hidden entries' { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; }; + + $Result.Exists | Should -BeTrue; + $Result.FileCount | Should -Be 3; + $Result.FolderCount | Should -Be 1; + $Result.TotalCount | Should -Be 4; + $Result.TotalSize | Should -Be 2150; + $Result.SmallestFile | Should -Be 50; + $Result.LargestFile | Should -Be 2000; + $Result.AverageSize | Should -Be 716.67; + @($Result.FileList).Count | Should -Be 0; + } + + It 'descends into every subdirectory with Recurse, but not into hidden ones' { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'Recurse' = $true; }; + + $Result.FileCount | Should -Be 5; + $Result.FolderCount | Should -Be 2; + $Result.TotalSize | Should -Be 7151; + $Result.SmallestFile | Should -Be 1; + $Result.LargestFile | Should -Be 5000; + } + + It 'matches the file names case-insensitively and still scans non-matching folders' { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'Recurse' = $true; 'FileNames' = @('*.LOG'); }; + + $Result.FileCount | Should -Be 4; + $Result.FolderCount | Should -Be 0; + } + + It 'keeps entries matching any of several name patterns' { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'FileNames' = @('a.*', '*.txt'); }; + + $Result.FileCount | Should -Be 2; + } + + It 'filters by the last write time' { + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'ChangeOlderThan' = '5d'; }).FileCount | Should -Be 2; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'ChangeOlderThan' = '5d'; }).FolderCount | Should -Be 0; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'ChangeYoungerThan' = '1d'; }).FileCount | Should -Be 1; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'ChangeYoungerThan' = '4d'; }).FolderCount | Should -Be 1; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'ChangeTimeEqual' = '10d'; }).FileCount | Should -Be 1; + } + + It 'filters by the creation and the last access time' { + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'CreationOlderThan' = '20d'; }).FileCount | Should -Be 1; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'CreationYoungerThan' = '20d'; }).FileCount | Should -Be 2; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'AccessOlderThan' = '20d'; }).FileCount | Should -Be 1; + } + + It 'filters files by size, accepts plain numbers as bytes and never keeps folders' { + $Larger = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'Recurse' = $true; 'FileSizeGreaterThan' = '1KB'; }; + $Larger.FileCount | Should -Be 2; + $Larger.FolderCount | Should -Be 0; + + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'FileSizeSmallerThan' = '100'; }).FileCount | Should -Be 1; + } + + It 'combines every given filter with AND' { + $Result = Invoke-TestDirectory -Arguments @{ + 'Path' = $script:Root; + 'Recurse' = $true; + 'FileNames' = @('*.log'); + 'ChangeYoungerThan' = '3d'; + 'FileSizeGreaterThan' = '1KB'; + }; + + $Result.FileCount | Should -Be 2; + $Result.TotalSize | Should -Be 7000; + } + + It 'returns the kept entries with IncludeFileList' { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'IncludeFileList' = $true; }; + + [array]$Names = @($Result.FileList | ForEach-Object { $_.Name } | Sort-Object); + $Names | Should -Be @('a.log', 'b.log', 'c.txt', 'sub'); + } + + It 'resolves a relative path against the current location' { + $Result = & $script:IcingaModule { + param ($Root); + + Push-Location -Path $Root; + try { + Get-IcingaDirectoryInformation -Path 'sub'; + } finally { + Pop-Location; + } + } $script:Root; + + $Result.FileCount | Should -Be 1; + $Result.FolderCount | Should -Be 1; + } + + It 'rejects an invalid filter value with DirectoryFilterInvalid' { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'ChangeOlderThan' = '20MB'; }; + $Result.GetType().Name | Should -Be 'IcingaError'; + $Result.ReturnCode | Should -Be 'DirectoryFilterInvalid'; + $Result.Message | Should -Be 'The value "20MB" of -ChangeOlderThan is not a valid duration such as 20d, 12h or 30m'; + + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'FileSizeGreaterThan' = 'abc'; }).ReturnCode | Should -Be 'DirectoryFilterInvalid'; + } + + It 'reports a missing path, or an empty result with IgnoreMissingPath' { + [string]$Missing = Join-Path -Path $TestDrive -ChildPath 'missing'; + + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $Missing; }; + $Result.ReturnCode | Should -Be 'DirectoryPathNotFound'; + $Result.Message | Should -Be ([string]::Format('The directory "{0}" does not exist on this system', $Missing)); + + $Empty = Invoke-TestDirectory -Arguments @{ 'Path' = $Missing; 'IgnoreMissingPath' = $true; }; + $Empty.Exists | Should -BeFalse; + $Empty.FileCount | Should -Be 0; + + (Invoke-TestDirectory -Arguments @{ 'Path' = ''; }).ReturnCode | Should -Be 'DirectoryPathMissing'; + } + + It 'reports a directory that cannot be listed with DirectoryAccessDenied' { + [string]$Locked = Join-Path -Path $TestDrive -ChildPath 'locked'; + New-Item -Path $Locked -ItemType Directory -Force | Out-Null; + + $Rule = New-Object System.Security.AccessControl.FileSystemAccessRule( + [System.Security.Principal.WindowsIdentity]::GetCurrent().Name, + [System.Security.AccessControl.FileSystemRights]::ListDirectory, + [System.Security.AccessControl.AccessControlType]::Deny + ); + $Acl = Get-Acl -Path $Locked; + $Acl.AddAccessRule($Rule); + Set-Acl -Path $Locked -AclObject $Acl; + + try { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $Locked; }; + $Result.ReturnCode | Should -Be 'DirectoryAccessDenied'; + $Result.Message | Should -Be ([string]::Format('Access to the directory "{0}" was denied', $Locked)); + } finally { + $Acl = Get-Acl -Path $Locked; + [void]$Acl.RemoveAccessRule($Rule); + Set-Acl -Path $Locked -AclObject $Acl; + } + } + + It 'scans 5000 files with filters in one pass within the time budget' { + [string]$Large = Join-Path -Path $TestDrive -ChildPath 'large'; + New-Item -Path $Large -ItemType Directory -Force | Out-Null; + + for ($i = 0; $i -lt 5000; $i++) { + [System.IO.File]::WriteAllBytes((Join-Path -Path $Large -ChildPath ([string]::Format('file{0}.log', $i))), [byte[]]::new($i % 10)); + } + + $Watch = [System.Diagnostics.Stopwatch]::StartNew(); + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $Large; 'FileNames' = @('*.log'); 'ChangeYoungerThan' = '1h'; 'FileSizeGreaterThan' = '4'; }; + $Watch.Stop(); + + $Result.FileCount | Should -Be 2500; + $Watch.ElapsedMilliseconds | Should -BeLessThan 5000; + } +} diff --git a/Tests/Get-IcingaDiskInformation.Tests.ps1 b/Tests/Get-IcingaDiskInformation.Tests.ps1 new file mode 100644 index 0000000..8f25f92 --- /dev/null +++ b/Tests/Get-IcingaDiskInformation.Tests.ps1 @@ -0,0 +1,179 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Get-IcingaDiskInformation' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + # Runs the provider inside the module scope with Get-IcingaWindowsInformation + # shadowed by a function that serves the stub instances per class, or an + # IcingaError for every class listed in FailingClasses. + function Invoke-TestDiskInformation() + { + param ( + [string]$Entrypoint = 'PhysicalDisk', + [hashtable]$StubData = @{ }, + [array]$FailingClasses = @() + ); + + return (& $script:IcingaModule { + param ($Entrypoint, $StubData, $FailingClasses); + + function Get-IcingaWindowsInformation() + { + param ( + [string]$ClassName = '', + [string]$Namespace = '', + [string]$Filter = '', + [array]$Property = @() + ); + + if ($FailingClasses -contains $ClassName) { + return [IcingaError]::new('WindowsInformationClassUnknown', [string]::Format('Simulated failure of {0}', $ClassName), @{ }); + } + + if ($StubData.ContainsKey($ClassName)) { + return ,@($StubData[$ClassName]); + } + + return ,@(); + } + + $Value = Get-IcingaDiskInformation -Entrypoint $Entrypoint; + + return @{ + 'Value' = $Value; + 'IsError' = ($Value -is [IcingaError]); + }; + } $Entrypoint $StubData $FailingClasses); + } + + $script:StubData = @{ + 'Win32_Volume' = @( + [PSCustomObject]@{ 'DeviceID' = '\\?\Volume{c}\'; 'Name' = 'C:\'; 'DriveLetter' = 'C:'; 'Label' = 'System'; 'FileSystem' = 'NTFS'; 'Capacity' = [uint64]500000000000; 'FreeSpace' = [uint64]100000000000; }, + [PSCustomObject]@{ 'DeviceID' = '\\?\Volume{r}\'; 'Name' = '\\?\Volume{r}\'; 'DriveLetter' = $null; 'Label' = 'Recovery'; 'FileSystem' = 'NTFS'; 'Capacity' = [uint64]1000000000; 'FreeSpace' = [uint64]100000000; }, + [PSCustomObject]@{ 'DeviceID' = '\\?\Volume{x}\'; 'Name' = '\\?\Volume{x}\'; 'DriveLetter' = $null; 'Label' = $null; 'FileSystem' = 'RAW'; 'Capacity' = $null; 'FreeSpace' = $null; } + ); + 'MSFT_Partition' = @( + [PSCustomObject]@{ 'DiskNumber' = [uint32]0; 'PartitionNumber' = [uint32]1; 'DriveLetter' = [char]0; 'AccessPaths' = @('\\?\Volume{e}\'); 'Size' = [uint64]200000000; 'Offset' = [uint64]1048576; 'GptType' = '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}'; 'MbrType' = $null; 'IsBoot' = $false; 'IsSystem' = $true; 'IsActive' = $false; 'IsHidden' = $true; }, + [PSCustomObject]@{ 'DiskNumber' = [uint32]0; 'PartitionNumber' = [uint32]3; 'DriveLetter' = [char]'C'; 'AccessPaths' = @('C:\', '\\?\Volume{c}\'); 'Size' = [uint64]500000000000; 'Offset' = [uint64]227540992; 'GptType' = '{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}'; 'MbrType' = $null; 'IsBoot' = $true; 'IsSystem' = $false; 'IsActive' = $false; 'IsHidden' = $false; }, + [PSCustomObject]@{ 'DiskNumber' = [uint32]0; 'PartitionNumber' = [uint32]4; 'DriveLetter' = [char]0; 'AccessPaths' = @('\\?\Volume{r}\'); 'Size' = [uint64]1000000000; 'Offset' = [uint64]500300000000; 'GptType' = '{de94bba4-06d1-4d40-a16a-bfd50179d6ac}'; 'MbrType' = $null; 'IsBoot' = $false; 'IsSystem' = $false; 'IsActive' = $false; 'IsHidden' = $true; }, + [PSCustomObject]@{ 'DiskNumber' = [uint32]1; 'PartitionNumber' = [uint32]1; 'DriveLetter' = [char]'E'; 'AccessPaths' = @('E:\'); 'Size' = [uint64]100000000000; 'Offset' = [uint64]1048576; 'GptType' = $null; 'MbrType' = [uint16]7; 'IsBoot' = $false; 'IsSystem' = $false; 'IsActive' = $true; 'IsHidden' = $false; } + ); + 'MSFT_Disk' = @( + [PSCustomObject]@{ 'Number' = [uint32]0; 'FriendlyName' = 'NVMe Disk'; 'Model' = 'NVMe Disk'; 'Manufacturer' = 'Vendor'; 'SerialNumber' = 'SERIAL0 '; 'UniqueId' = 'eui.0000'; 'Size' = [uint64]512000000000; 'BusType' = [uint16]17; 'HealthStatus' = [uint16]0; 'OperationalStatus' = @([uint16]53264); 'IsOffline' = $false; 'OfflineReason' = [uint16]0; 'IsReadOnly' = $false; 'IsBoot' = $true; 'IsSystem' = $true; 'IsClustered' = $false; 'PartitionStyle' = [uint16]2; 'Location' = 'PCI Slot 8'; }, + [PSCustomObject]@{ 'Number' = [uint32]1; 'FriendlyName' = 'SAN LUN'; 'Model' = 'LUN'; 'Manufacturer' = 'SAN'; 'SerialNumber' = 'SAN-SERIAL'; 'UniqueId' = '600A0B80'; 'Size' = [uint64]100000000000; 'BusType' = [uint16]6; 'HealthStatus' = [uint16]0; 'OperationalStatus' = @([uint16]53264); 'IsOffline' = $false; 'OfflineReason' = [uint16]0; 'IsReadOnly' = $true; 'IsBoot' = $false; 'IsSystem' = $false; 'IsClustered' = $true; 'PartitionStyle' = [uint16]1; 'Location' = 'Fibre Channel'; } + ); + 'MSFT_PhysicalDisk' = @( + [PSCustomObject]@{ 'DeviceId' = '0'; 'MediaType' = [uint16]4; 'SpindleSpeed' = [uint32]0; } + ); + 'MPIO_DISK_INFO' = @( + [PSCustomObject]@{ 'InstanceName' = 'ROOT\MPIO\0000_0'; 'DriveInfo' = @([PSCustomObject]@{ 'Name' = 'MPIO Disk1'; 'NumberPaths' = [uint32]4; 'SerialNumber' = '600A0B80'; }); } + ); + }; + } + + Context 'Volume entrypoint' { + It 'returns every volume keyed by its volume path with sizes in bytes' { + $Volumes = (Invoke-TestDiskInformation -Entrypoint 'Volume' -StubData $script:StubData).Value; + $Volumes.Count | Should -Be 3; + $Volumes['\\?\Volume{c}\'].Name | Should -Be 'C:\'; + $Volumes['\\?\Volume{c}\'].DriveLetter | Should -Be 'C:'; + $Volumes['\\?\Volume{c}\'].Size | Should -Be 500000000000; + $Volumes['\\?\Volume{c}\'].FreeSpace | Should -Be 100000000000; + $Volumes['\\?\Volume{c}\'].UsedSpace | Should -Be 400000000000; + $Volumes['\\?\Volume{r}\'].Label | Should -Be 'Recovery'; + } + + It 'links each volume to its disk and partition through the access paths' { + $Volumes = (Invoke-TestDiskInformation -Entrypoint 'Volume' -StubData $script:StubData).Value; + $Volumes['\\?\Volume{c}\'].DiskNumber | Should -Be 0; + $Volumes['\\?\Volume{c}\'].PartitionNumber | Should -Be 3; + $Volumes['\\?\Volume{c}\'].PartitionId | Should -Be 'Disk #0, Partition #3'; + $Volumes['\\?\Volume{x}\'].DiskNumber | Should -BeNullOrEmpty; + } + + It 'reports unknown sizes as $null' { + $Volume = (Invoke-TestDiskInformation -Entrypoint 'Volume' -StubData $script:StubData).Value['\\?\Volume{x}\']; + $Volume.Size | Should -BeNullOrEmpty; + $Volume.UsedSpace | Should -BeNullOrEmpty; + } + + It 'still returns the volumes when the partition data is unavailable' { + $Result = Invoke-TestDiskInformation -Entrypoint 'Volume' -StubData $script:StubData -FailingClasses 'MSFT_Partition'; + $Result.IsError | Should -BeFalse; + $Result.Value['\\?\Volume{c}\'].Size | Should -Be 500000000000; + $Result.Value['\\?\Volume{c}\'].DiskNumber | Should -BeNullOrEmpty; + } + + It 'returns the IcingaError when the volumes cannot be read' { + $Result = Invoke-TestDiskInformation -Entrypoint 'Volume' -StubData $script:StubData -FailingClasses 'Win32_Volume'; + $Result.IsError | Should -BeTrue; + $Result.Value.Message | Should -Be 'Simulated failure of Win32_Volume'; + } + } + + Context 'Partition entrypoint' { + It 'returns every partition with drive letter and linked volume' { + $Partitions = (Invoke-TestDiskInformation -Entrypoint 'Partition' -StubData $script:StubData).Value; + $Partitions.Count | Should -Be 4; + $Partitions['Disk #0, Partition #3'].DriveLetter | Should -Be 'C:'; + $Partitions['Disk #0, Partition #3'].VolumeId | Should -Be '\\?\Volume{c}\'; + $Partitions['Disk #0, Partition #3'].Volume.Name | Should -Be 'C:\'; + $Partitions['Disk #0, Partition #3'].IsBoot | Should -BeTrue; + $Partitions['Disk #0, Partition #1'].DriveLetter | Should -Be ''; + $Partitions['Disk #0, Partition #1'].Volume | Should -BeNullOrEmpty; + $Partitions['Disk #1, Partition #1'].MbrType | Should -Be 7; + } + + It 'returns the IcingaError when the partitions cannot be read' { + (Invoke-TestDiskInformation -Entrypoint 'Partition' -StubData $script:StubData -FailingClasses 'MSFT_Partition').IsError | Should -BeTrue; + } + } + + Context 'PhysicalDisk entrypoint' { + It 'returns every disk keyed by its number with media type and status' { + $Disks = (Invoke-TestDiskInformation -StubData $script:StubData).Value; + $Disks.Count | Should -Be 2; + $Disks['0'].FriendlyName | Should -Be 'NVMe Disk'; + $Disks['0'].SerialNumber | Should -Be 'SERIAL0'; + $Disks['0'].MediaType | Should -Be 4; + $Disks['0'].BusType | Should -Be 17; + $Disks['0'].OperationalStatus | Should -Be @(53264); + $Disks['0'].IsBoot | Should -BeTrue; + $Disks['1'].IsReadOnly | Should -BeTrue; + $Disks['1'].MediaType | Should -BeNullOrEmpty; + } + + It 'attaches partitions, volumes and drive letters to their disk' { + $Disks = (Invoke-TestDiskInformation -StubData $script:StubData).Value; + @($Disks['0'].Partitions.Keys | Sort-Object) | Should -Be @('1', '3', '4'); + $Disks['0'].DriveLetters | Should -Be @('C:'); + @($Disks['0'].Volumes | ForEach-Object { $_.Name }) | Should -Be @('C:\', '\\?\Volume{r}\'); + $Disks['1'].DriveLetters | Should -Be @('E:'); + } + + It 'matches the MPIO information by unique id' { + $Disks = (Invoke-TestDiskInformation -StubData $script:StubData).Value; + $Disks['1'].MPIO.Name | Should -Be 'MPIO Disk1'; + $Disks['1'].MPIO.NumberPaths | Should -Be 4; + $Disks['1'].MPIO.InstanceName | Should -Be 'ROOT\MPIO\0000_0'; + $Disks['0'].MPIO | Should -BeNullOrEmpty; + } + + It 'leaves MPIO and media type empty when their classes are unavailable' { + $Result = Invoke-TestDiskInformation -StubData $script:StubData -FailingClasses 'MPIO_DISK_INFO', 'MSFT_PhysicalDisk'; + $Result.IsError | Should -BeFalse; + $Result.Value['1'].MPIO | Should -BeNullOrEmpty; + $Result.Value['0'].MediaType | Should -BeNullOrEmpty; + } + + It 'returns the IcingaError when the disks cannot be read' { + (Invoke-TestDiskInformation -StubData $script:StubData -FailingClasses 'MSFT_Disk').IsError | Should -BeTrue; + } + } +} diff --git a/Tests/Get-IcingaWindowsInformation.Tests.ps1 b/Tests/Get-IcingaWindowsInformation.Tests.ps1 new file mode 100644 index 0000000..f34c8f8 --- /dev/null +++ b/Tests/Get-IcingaWindowsInformation.Tests.ps1 @@ -0,0 +1,130 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Get-IcingaWindowsInformation' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + # Runs the query inside the module scope with Get-CimInstance shadowed by a + # function. The result is wrapped in a hashtable so its type survives the + # pipeline, and IcingaError is only resolvable inside the module scope. + function Invoke-TestWindowsInformation() + { + param ( + [hashtable]$Arguments = @{ }, + [array]$StubData = @(), + [string]$FailCode = '', + [switch]$EchoArguments + ); + + return (& $script:IcingaModule { + param ($Arguments, $StubData, $FailCode, $EchoArguments); + + class FakeCimException : System.Exception + { + [string]$NativeErrorCode = ''; + + FakeCimException([string]$Message, [string]$Code) : base($Message) + { + $this.NativeErrorCode = $Code; + } + } + + function Get-CimInstance() + { + [CmdletBinding()] + param ( + [string]$ClassName = '', + [string]$Namespace = '', + [string]$Filter = '', + [string[]]$Property = @() + ); + + if (-not [string]::IsNullOrEmpty($FailCode)) { + throw [FakeCimException]::new('Simulated CIM failure', $FailCode); + } + + if ($EchoArguments) { + return [PSCustomObject]@{ + 'Bound' = @($PSBoundParameters.Keys); + 'ClassName' = $ClassName; + 'Namespace' = $Namespace; + 'Filter' = $Filter; + 'Property' = $Property; + }; + } + + return $StubData; + } + + $Value = Get-IcingaWindowsInformation @Arguments; + + return @{ + 'Value' = $Value; + 'IsArray' = ($Value -is [array]); + 'IsError' = ($Value -is [IcingaError]); + }; + } $Arguments $StubData $FailCode $EchoArguments); + } + } + + Context 'Successful queries' { + It 'returns the instances as an array, even a single one' { + $Result = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'Win32_Service'; } -StubData @([PSCustomObject]@{ 'Name' = 'Spooler'; }); + $Result.IsArray | Should -BeTrue; + $Result.Value.Count | Should -Be 1; + $Result.Value[0].Name | Should -Be 'Spooler'; + } + + It 'returns an empty array when nothing matches' { + $Result = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'Win32_Service'; }; + $Result.IsArray | Should -BeTrue; + $Result.Value.Count | Should -Be 0; + } + + It 'uses root/cimv2 and passes filter and properties only when given' { + $Plain = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'Win32_Volume'; } -EchoArguments; + $Plain.Value[0].Namespace | Should -Be 'root/cimv2'; + $Plain.Value[0].Bound | Should -Not -Contain 'Filter'; + $Plain.Value[0].Bound | Should -Not -Contain 'Property'; + + $Full = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'MSFT_Disk'; 'Namespace' = 'root/Microsoft/Windows/Storage'; 'Filter' = 'Number = 0'; 'Property' = @('Number', 'Size'); } -EchoArguments; + $Full.Value[0].Namespace | Should -Be 'root/Microsoft/Windows/Storage'; + $Full.Value[0].Filter | Should -Be 'Number = 0'; + $Full.Value[0].Property | Should -Be @('Number', 'Size'); + } + } + + Context 'Failed queries' { + It 'maps the CIM error to ' -ForEach @( + @{ 'Code' = 'InvalidClass'; 'ReturnCode' = 'WindowsInformationClassUnknown'; }, + @{ 'Code' = 'InvalidNamespace'; 'ReturnCode' = 'WindowsInformationNamespaceInvalid'; }, + @{ 'Code' = 'AccessDenied'; 'ReturnCode' = 'WindowsInformationAccessDenied'; }, + @{ 'Code' = 'InvalidQuery'; 'ReturnCode' = 'WindowsInformationInvalidQuery'; }, + @{ 'Code' = 'NoSuchProperty'; 'ReturnCode' = 'WindowsInformationInvalidQuery'; }, + @{ 'Code' = 'Failed'; 'ReturnCode' = 'WindowsInformationQueryFailed'; } + ) { + $Result = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'Win32_Foo'; 'Namespace' = 'root/test'; } -FailCode $Code; + $Result.IsError | Should -BeTrue; + $Result.Value.ReturnCode | Should -Be $ReturnCode; + } + + It 'names class, namespace and reason in the error message and data' { + $Result = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'MPIO_DISK_INFO'; 'Namespace' = 'root/wmi'; } -FailCode 'InvalidClass'; + $Result.Value.Message | Should -Be 'The requested CIM class does not exist on this system: Class "MPIO_DISK_INFO", Namespace "root/wmi": Simulated CIM failure'; + $Result.Value.Data['ClassName'] | Should -Be 'MPIO_DISK_INFO'; + $Result.Value.Data['Namespace'] | Should -Be 'root/wmi'; + } + + It 'returns an IcingaError instead of throwing for a missing class name' { + $Result = Invoke-TestWindowsInformation -Arguments @{ }; + $Result.IsError | Should -BeTrue; + $Result.Value.ReturnCode | Should -Be 'WindowsInformationClassNameMissing'; + $Result.Value.Message | Should -Be 'No CIM class name was provided for the query'; + } + } +} diff --git a/Tests/IcingaServiceStartupType.Tests.ps1 b/Tests/IcingaServiceStartupType.Tests.ps1 new file mode 100644 index 0000000..a5f1a14 --- /dev/null +++ b/Tests/IcingaServiceStartupType.Tests.ps1 @@ -0,0 +1,83 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'IcingaServiceStartupType' { + BeforeAll { + # The data types live in the dot-sourced kernel and are only visible inside + # the script module scope. + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + } + + Context 'Enum values' { + It 'keeps the ServiceStartMode codes' { + $Codes = & $script:IcingaModule { + return @( + [int][IcingaServiceStartupType]::Boot, + [int][IcingaServiceStartupType]::System, + [int][IcingaServiceStartupType]::Automatic, + [int][IcingaServiceStartupType]::Manual, + [int][IcingaServiceStartupType]::Disabled, + [int][IcingaServiceStartupType]::Unknown + ); + }; + $Codes | Should -Be @(0, 1, 2, 3, 4, 5); + } + + It 'converts an array of names as a parameter type' { + $Converted = & $script:IcingaModule { + function Test-IcingaServiceStartupTypeParameter() + { + param ( + [IcingaServiceStartupType[]]$StartupType = @() + ); + + return ($StartupType -join ','); + } + + return (Test-IcingaServiceStartupTypeParameter -StartupType 'automatic', 'Disabled'); + }; + $Converted | Should -Be 'Automatic,Disabled'; + } + } + + Context 'IcingaServiceStartupTypeMap' { + It 'resolves the Win32_Service start modes' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaServiceStartupTypeMap]::Resolve('Boot'), + [string][IcingaServiceStartupTypeMap]::Resolve('System'), + [string][IcingaServiceStartupTypeMap]::Resolve('Auto'), + [string][IcingaServiceStartupTypeMap]::Resolve('Manual'), + [string][IcingaServiceStartupTypeMap]::Resolve('Disabled') + ); + }; + $Resolved | Should -Be @('Boot', 'System', 'Automatic', 'Manual', 'Disabled'); + } + + It 'resolves names in any casing and numeric codes' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaServiceStartupTypeMap]::Resolve('automatic'), + [string][IcingaServiceStartupTypeMap]::Resolve(3) + ); + }; + $Resolved | Should -Be @('Automatic', 'Manual'); + } + + It 'resolves unmappable values to Unknown' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaServiceStartupTypeMap]::Resolve($null), + [string][IcingaServiceStartupTypeMap]::Resolve(''), + [string][IcingaServiceStartupTypeMap]::Resolve('Delayed'), + [string][IcingaServiceStartupTypeMap]::Resolve(42) + ); + }; + $Resolved | Should -Be @('Unknown', 'Unknown', 'Unknown', 'Unknown'); + } + } +} diff --git a/Tests/IcingaServiceStatus.Tests.ps1 b/Tests/IcingaServiceStatus.Tests.ps1 new file mode 100644 index 0000000..d5d560b --- /dev/null +++ b/Tests/IcingaServiceStatus.Tests.ps1 @@ -0,0 +1,106 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'IcingaServiceStatus' { + BeforeAll { + # The data types live in the dot-sourced kernel and are only visible inside + # the script module scope. + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + } + + Context 'Enum values' { + It 'keeps the ServiceControllerStatus codes used by the state perfdata' { + $Codes = & $script:IcingaModule { + return @( + [int][IcingaServiceStatus]::Unknown, + [int][IcingaServiceStatus]::Stopped, + [int][IcingaServiceStatus]::StartPending, + [int][IcingaServiceStatus]::StopPending, + [int][IcingaServiceStatus]::Running, + [int][IcingaServiceStatus]::ContinuePending, + [int][IcingaServiceStatus]::PausePending, + [int][IcingaServiceStatus]::Paused + ); + }; + $Codes | Should -Be @(0, 1, 2, 3, 4, 5, 6, 7); + } + + It 'converts names in any casing and codes as a parameter type' { + $Converted = & $script:IcingaModule { + function Test-IcingaServiceStatusParameter() + { + param ( + [IcingaServiceStatus]$Status = 'Running' + ); + + return [string]$Status; + } + + return @( + (Test-IcingaServiceStatusParameter), + (Test-IcingaServiceStatusParameter -Status 'stoppending'), + (Test-IcingaServiceStatusParameter -Status 7) + ); + }; + $Converted | Should -Be @('Running', 'StopPending', 'Paused'); + } + + It 'rejects an unknown name as a parameter value' { + { + & $script:IcingaModule { + function Test-IcingaServiceStatusParameter() + { + param ( + [IcingaServiceStatus]$Status = 'Running' + ); + + return $Status; + } + + Test-IcingaServiceStatusParameter -Status 'Sleeping'; + }; + } | Should -Throw; + } + } + + Context 'IcingaServiceStatusMap' { + It 'resolves Win32_Service states with blanks' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaServiceStatusMap]::Resolve('Running'), + [string][IcingaServiceStatusMap]::Resolve('Start Pending'), + [string][IcingaServiceStatusMap]::Resolve('Continue Pending'), + [string][IcingaServiceStatusMap]::Resolve('Unknown') + ); + }; + $Resolved | Should -Be @('Running', 'StartPending', 'ContinuePending', 'Unknown'); + } + + It 'resolves names in any casing and numeric codes' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaServiceStatusMap]::Resolve('paused'), + [string][IcingaServiceStatusMap]::Resolve(1), + [string][IcingaServiceStatusMap]::Resolve('4') + ); + }; + $Resolved | Should -Be @('Paused', 'Stopped', 'Running'); + } + + It 'resolves unmappable values to Unknown' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaServiceStatusMap]::Resolve($null), + [string][IcingaServiceStatusMap]::Resolve(''), + [string][IcingaServiceStatusMap]::Resolve('Sleeping'), + [string][IcingaServiceStatusMap]::Resolve(99) + ); + }; + $Resolved | Should -Be @('Unknown', 'Unknown', 'Unknown', 'Unknown'); + } + } +} diff --git a/Tests/Invoke-IcingaCheckCPU.Tests.ps1 b/Tests/Invoke-IcingaCheckCPU.Tests.ps1 new file mode 100644 index 0000000..a133fc5 --- /dev/null +++ b/Tests/Invoke-IcingaCheckCPU.Tests.ps1 @@ -0,0 +1,171 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckCPU' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Builds the -StructureByInstance result of Get-IcingaPerformanceCounter for + # '\Processor Information(*)\% Processor Time'. A string value becomes the + # counter error of that instance. + function New-TestCpuCounter() + { + param ( + [hashtable]$Instances = @{ } + ); + + [hashtable]$Result = @{ }; + + foreach ($Instance in $Instances.Keys) { + $Leaf = @{ 'value' = [decimal]0; 'sample' = $null; 'help' = ''; 'type' = ''; 'error' = $null; }; + + if ($Instances[$Instance] -is [string]) { + $Leaf['error'] = $Instances[$Instance]; + } else { + $Leaf['value'] = [decimal]$Instances[$Instance]; + } + + $Result[$Instance] = @{ 'Processor Information' = @{ '% Processor Time' = $Leaf; }; }; + } + + return $Result; + } + + # Runs the plugin inside the module scope with the performance counter + # functions shadowed, so the check works on the given counter values. + function Invoke-TestCpuCheck() + { + param ( + $StubData = $null, + [hashtable]$Arguments = @{ } + ); + + return (& $script:IcingaModule { + param ($StubData, $Arguments); + + function New-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @() + ); + } + + function Get-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @(), + [int]$TimeoutMs = 5000, + [switch]$StructureByInstance = $false + ); + + return $StubData; + } + + Invoke-IcingaCheckCPU @Arguments; + } $StubData $Arguments); + } + + # Windows' own totals carry wrong values on purpose: the plugin must average the + # cores instead of reading these instances. + $script:TwoNodes = New-TestCpuCounter -Instances @{ + '0,1' = 95; + '0,0' = 5; + '0,_Total' = 77; + '1,0' = 10; + '1,_Total' = 99; + '_Total' = 1; + }; + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'writes the perfdata per core, per NUMA node and in total in natural order' { + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'Warning' = '80'; 'Critical' = '90'; } | Out-Null; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + '0_0::ifw_cpu::load=5%;80;90;0;100', + '0_1::ifw_cpu::load=95%;80;90;0;100', + '0_total::ifw_cpu::load=50%;80;90;0;100', + '1_2::ifw_cpu::load=10%;80;90;0;100', + '1_total::ifw_cpu::load=10%;80;90;0;100', + 'totalload::ifw_cpu::load=36.67%;80;90;0;100' + ); + } + + It 'groups the cores into one container per NUMA node and numbers them across all nodes' { + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'Verbosity' = 2; } | Should -Be 0; + + [array]$Lines = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n"; + $Lines[0] | Should -Be '[OK] CPU Load: 6 Ok'; + $Lines[1] | Should -Be '\_ [OK] NUMA Node #0'; + $Lines[2] | Should -Match '^ \\_ \[OK\] Core #0: '; + $Lines[4] | Should -Match '^ \\_ \[OK\] Node Total: '; + $Lines[5] | Should -Be '\_ [OK] NUMA Node #1'; + $Lines[6] | Should -Be ' \_ [OK] Core #2: 10% is ok'; + $Lines[8] | Should -Match '^\\_ \[OK\] Overall Load: '; + } + + It 'reports the same node total and overall load on a single NUMA node' { + $Counters = New-TestCpuCounter -Instances @{ '0,0' = 13.18; '0,1' = 9.67; '0,2' = 6.52; '0,3' = 1.13; '0,_Total' = 7.44; '_Total' = 7.57; }; + + Invoke-TestCpuCheck -StubData $Counters | Should -Be 0; + + [array]$Perf = $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData; + $Perf[4] | Should -Be '0_total::ifw_cpu::load=7.62%;;;0;100'; + $Perf[5] | Should -Be 'totalload::ifw_cpu::load=7.62%;;;0;100'; + } + + It 'raises CRITICAL when a single core breaches the critical threshold' { + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'Warning' = '80'; 'Critical' = '90'; } | Should -Be 2; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match '^\[CRITICAL\] CPU Load: 1 Critical 5 Ok'; + $Result.Output | Should -Match ([regex]::Escape('[CRITICAL] Core #1: 95% is greater than threshold 90%')); + } + + It 'reports a core whose counter failed as UNKNOWN and averages the readable cores' { + $Counters = New-TestCpuCounter -Instances @{ '0,0' = 5; '0,1' = 'Counter not initialized'; '0,_Total' = 50; '_Total' = 50; }; + + Invoke-TestCpuCheck -StubData $Counters -Arguments @{ 'Warning' = '80'; } | Should -Be 3; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('[UNKNOWN] Core #1: Failed to read the performance counter: Counter not initialized')); + $Result.PerformanceData | Should -Contain '0_total::ifw_cpu::load=5%;80;;0;100'; + $Result.PerformanceData | Should -Contain 'totalload::ifw_cpu::load=5%;80;;0;100'; + } + + It 'reports the node total as UNKNOWN when no core of the node could be read' { + $Counters = New-TestCpuCounter -Instances @{ '0,0' = 5; '1,0' = 'Counter not initialized'; }; + + Invoke-TestCpuCheck -StubData $Counters -Arguments @{ 'Verbosity' = 2; } | Should -Be 3; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('[UNKNOWN] Node Total: Failed to read the performance counter: no core of this NUMA node could be read')); + $Result.PerformanceData | Should -Contain 'totalload::ifw_cpu::load=5%;;;0;100'; + } + + It 'returns UNKNOWN when no processor instance could be read' { + Invoke-TestCpuCheck -StubData $null | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] CPU Load: Failed to read the performance counter \Processor Information(*)\% Processor Time: no processor instance available'; + + Invoke-TestCpuCheck -StubData @{ } | Should -Be 3; + Invoke-TestCpuCheck -StubData (New-TestCpuCounter -Instances @{ '_Total' = 5; '0,_Total' = 5; }) | Should -Be 3; + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } +} diff --git a/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 b/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 new file mode 100644 index 0000000..14b5fa6 --- /dev/null +++ b/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 @@ -0,0 +1,207 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckDirectory' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Builds a result in the shape of Get-IcingaDirectoryInformation. + function New-TestDirectoryData() + { + param ( + [int]$FileCount = 0, + [int]$FolderCount = 0, + [long]$TotalSize = 0, + [long]$SmallestFile = 0, + [long]$LargestFile = 0, + [array]$FileList = @() + ); + + [double]$Average = 0; + + if ($FileCount -ne 0) { + $Average = [System.Math]::Round($TotalSize / $FileCount, 2); + } + + return @{ + 'Path' = 'C:\Backup'; + 'Exists' = $true; + 'FileCount' = $FileCount; + 'FolderCount' = $FolderCount; + 'TotalCount' = $FileCount + $FolderCount; + 'TotalSize' = $TotalSize; + 'LargestFile' = $LargestFile; + 'SmallestFile' = $SmallestFile; + 'AverageSize' = $Average; + 'FileList' = $FileList; + }; + } + + # Runs the plugin inside the module scope with Get-IcingaDirectoryInformation + # shadowed by a function, which records the arguments it was called with. + function Invoke-TestDirectoryCheck() + { + param ( + $StubData = $null, + [hashtable]$Arguments = @{ }, + [switch]$Fail = $false + ); + + return (& $script:IcingaModule { + param ($StubData, $Arguments, $Fail); + + function Get-IcingaDirectoryInformation() + { + param ( + [string]$Path = '', + [array]$FileNames = @( '*' ), + [switch]$Recurse = $false, + [string]$ChangeTimeEqual = '', + [string]$ChangeYoungerThan = '', + [string]$ChangeOlderThan = '', + [string]$CreationTimeEqual = '', + [string]$CreationYoungerThan = '', + [string]$CreationOlderThan = '', + [string]$AccessYoungerThan = '', + [string]$AccessOlderThan = '', + [string]$FileSizeGreaterThan = '', + [string]$FileSizeSmallerThan = '', + [switch]$IncludeFileList = $false, + [switch]$IgnoreMissingPath = $false + ); + + $Global:IcingaTestDirectoryCall = $PSBoundParameters; + + if ($Fail) { + return [IcingaError]::new('DirectoryAccessDenied', 'Access to the directory "C:\Backup" was denied', @{ }); + } + + return $StubData; + } + + Invoke-IcingaCheckDirectory @Arguments; + } $StubData $Arguments $Fail); + } + + # 3 files of 1KiB, 2KiB and 3KiB, one folder. + $script:Backup = New-TestDirectoryData -FileCount 3 -FolderCount 1 -TotalSize 6144 -SmallestFile 1024 -LargestFile 3072; + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + Remove-Variable -Name 'IcingaTestDirectoryCall' -Scope Global -ErrorAction Ignore; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'writes one metric per statistic with the path as index' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'Warning' = '5'; 'Critical' = '10'; } | Should -Be 0; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + 'cbackup::ifw_directory::files=3;5;10;;', + 'cbackup::ifw_directory::folders=1;;;;', + 'cbackup::ifw_directory::totalsize=6144B;;;;', + 'cbackup::ifw_directory::smallestfile=1024B;;;;', + 'cbackup::ifw_directory::largestfile=3072B;;;;', + 'cbackup::ifw_directory::averagefile=2048B;;;;' + ); + } + + It 'lists every statistic and the informational file found entry' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'Verbosity' = 2; } | Should -Be 0; + + [array]$Lines = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n"; + $Lines[0] | Should -Be '[OK] Directory Check: "C:\Backup": 7 Ok'; + $Lines[1] | Should -Be '\_ [OK] File Count: 3 is ok'; + $Lines[3] | Should -Be '\_ [OK] Total Size: 6KiB is ok'; + $Lines[6] | Should -Be '\_ [OK] Average File Size: 2KiB is ok'; + $Lines[7] | Should -Be '\_ [INFO] File Found: Yes'; + } + + It 'raises the state when the file count or a size breaches its threshold' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'Critical' = '2'; 'WarningTotalSize' = '5KiB'; } | Should -Be 2; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match ([regex]::Escape('[CRITICAL] Directory Check: "C:\Backup": 1 Critical 1 Warning 5 Ok')); + $Output | Should -Match ([regex]::Escape('[CRITICAL] File Count: 3 is greater than threshold 2')); + $Output | Should -Match ([regex]::Escape('[WARNING] Total Size: 6KiB is greater than threshold 5KiB')); + } + + It 'adds the folders to the file count with CountFolderAsFile' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'Critical' = '3'; 'CountFolderAsFile' = $true; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'cbackup::ifw_directory::files=4;;3;;'; + } + + It 'passes the filters to the provider and treats a missing path as empty only with OverrideNotFound' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'Recurse' = $true; 'FileNames' = @('*.bak'); 'ChangeOlderThan' = '1d'; 'FileSizeGreaterThan' = '1MB'; } | Out-Null; + + $Global:IcingaTestDirectoryCall['Recurse'] | Should -BeTrue; + $Global:IcingaTestDirectoryCall['FileNames'] | Should -Be @('*.bak'); + $Global:IcingaTestDirectoryCall['ChangeOlderThan'] | Should -Be '1d'; + $Global:IcingaTestDirectoryCall['FileSizeGreaterThan'] | Should -Be '1MB'; + $Global:IcingaTestDirectoryCall['IgnoreMissingPath'] | Should -BeFalse; + $Global:IcingaTestDirectoryCall['IncludeFileList'] | Should -BeFalse; + + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'OverrideNotFound' = 'Critical'; } | Out-Null; + $Global:IcingaTestDirectoryCall['IgnoreMissingPath'] | Should -BeTrue; + } + + It 'reports the OverrideNotFound state when nothing matches' { + $Empty = New-TestDirectoryData; + + Invoke-TestDirectoryCheck -StubData $Empty -Arguments @{ 'Path' = 'C:\Backup'; 'OverrideNotFound' = 'Critical'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[CRITICAL] Directory Check: `"C:\Backup`": 1 Critical 6 Ok [CRITICAL] File Found`n\_ [CRITICAL] File Found: No"; + + Invoke-TestDirectoryCheck -StubData $Empty -Arguments @{ 'Path' = 'C:\Backup'; 'OverrideNotFound' = 'Warning'; } | Should -Be 1; + Invoke-TestDirectoryCheck -StubData $Empty -Arguments @{ 'Path' = 'C:\Backup'; 'OverrideNotFound' = 'Ok'; } | Should -Be 0; + Invoke-TestDirectoryCheck -StubData $Empty -Arguments @{ 'Path' = 'C:\Backup'; } | Should -Be 0; + } + + It 'reports OK for found files even with OverrideNotFound' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'OverrideNotFound' = 'Critical'; 'Verbosity' = 2; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[OK] File Found: Yes')); + } + + It 'reports a provider failure as UNKNOWN with its reason' { + Invoke-TestDirectoryCheck -Fail -Arguments @{ 'Path' = 'C:\Backup'; } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Directory Check: "C:\Backup": Access to the directory "C:\Backup" was denied'; + } + + It 'lists the files sorted by path with ShowFileList without counting them' { + [string]$ListRoot = Join-Path -Path $TestDrive -ChildPath 'list'; + New-Item -Path (Join-Path -Path $ListRoot -ChildPath 'folder') -ItemType Directory -Force | Out-Null; + [System.IO.File]::WriteAllBytes((Join-Path -Path $ListRoot -ChildPath 'b.bak'), [byte[]]::new(2048)); + [System.IO.File]::WriteAllBytes((Join-Path -Path $ListRoot -ChildPath 'a.bak'), [byte[]]::new(1024)); + + [array]$Entries = @( + [System.IO.FileInfo]::new((Join-Path -Path $ListRoot -ChildPath 'b.bak')), + [System.IO.DirectoryInfo]::new((Join-Path -Path $ListRoot -ChildPath 'folder')), + [System.IO.FileInfo]::new((Join-Path -Path $ListRoot -ChildPath 'a.bak')) + ); + $Data = New-TestDirectoryData -FileCount 2 -FolderCount 1 -TotalSize 3072 -SmallestFile 1024 -LargestFile 2048 -FileList $Entries; + + Invoke-TestDirectoryCheck -StubData $Data -Arguments @{ 'Path' = 'C:\Backup'; 'ShowFileList' = $true; } | Should -Be 0; + + $Global:IcingaTestDirectoryCall['IncludeFileList'] | Should -BeTrue; + + [array]$Lines = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n"; + $Lines[0] | Should -Be '[OK] Directory Check: "C:\Backup": 7 Ok'; + $Lines[8] | Should -Be '\_ [INFO] File List'; + $Lines[9] | Should -Be ([string]::Format(' \_ [INFO] {0}: 1KiB', (Join-Path -Path $ListRoot -ChildPath 'a.bak'))); + $Lines[10] | Should -Be ([string]::Format(' \_ [INFO] {0}: 2KiB', (Join-Path -Path $ListRoot -ChildPath 'b.bak'))); + $Lines[11] | Should -Be ([string]::Format(' \_ [INFO] {0}: Folder', (Join-Path -Path $ListRoot -ChildPath 'folder'))); + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } +} diff --git a/Tests/Invoke-IcingaCheckMemory.Tests.ps1 b/Tests/Invoke-IcingaCheckMemory.Tests.ps1 new file mode 100644 index 0000000..c046059 --- /dev/null +++ b/Tests/Invoke-IcingaCheckMemory.Tests.ps1 @@ -0,0 +1,188 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckMemory' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Builds the -StructureByInstance result of the two memory counters. A string + # value becomes the counter error. + function New-TestMemoryCounter() + { + param ( + $Available = [decimal]4294967296, + $PagesSec = [decimal]12.5 + ); + + [hashtable]$Memory = @{ }; + + foreach ($Counter in @(@('Available Bytes', $Available), @('Pages/sec', $PagesSec))) { + $Leaf = @{ 'value' = [decimal]0; 'sample' = $null; 'help' = ''; 'type' = ''; 'error' = $null; }; + + if ($Counter[1] -is [string]) { + $Leaf['error'] = $Counter[1]; + } else { + $Leaf['value'] = [decimal]$Counter[1]; + } + + $Memory[$Counter[0]] = $Leaf; + } + + return @{ 'Memory' = $Memory; }; + } + + # 16GiB installed, two page files of 2048MB (512MB used) and 1024MB (1000MB used). + function New-TestCimData() + { + param ( + [bool]$AutomaticManagedPagefile = $true, + [array]$PageFileSettings = @() + ); + + return @{ + 'Win32_ComputerSystem' = @([PSCustomObject]@{ 'TotalPhysicalMemory' = [uint64]17179869184; 'AutomaticManagedPagefile' = $AutomaticManagedPagefile; }); + 'Win32_PageFileUsage' = @( + [PSCustomObject]@{ 'Name' = 'D:\pagefile.sys'; 'AllocatedBaseSize' = [uint32]1024; 'CurrentUsage' = [uint32]1000; }, + [PSCustomObject]@{ 'Name' = 'C:\pagefile.sys'; 'AllocatedBaseSize' = [uint32]2048; 'CurrentUsage' = [uint32]512; } + ); + 'Win32_PageFileSetting' = $PageFileSettings; + }; + } + + # Runs the plugin inside the module scope with the CIM and performance counter + # functions shadowed, so the check works on the given data. + function Invoke-TestMemoryCheck() + { + param ( + [hashtable]$CimData = (New-TestCimData), + $Counters = (New-TestMemoryCounter), + [hashtable]$Arguments = @{ }, + [string]$FailClass = '' + ); + + return (& $script:IcingaModule { + param ($CimData, $Counters, $Arguments, $FailClass); + + function New-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @() + ); + } + + function Get-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @(), + [int]$TimeoutMs = 5000, + [switch]$StructureByInstance = $false + ); + + return $Counters; + } + + function Get-IcingaWindowsInformation() + { + param ( + [string]$ClassName = '', + [string]$Namespace = 'root/cimv2', + [string]$Filter = '', + [array]$Property = @() + ); + + if ($ClassName -eq $FailClass) { + return [IcingaError]::new('WindowsInformationAccessDenied', 'Simulated failure of ' + $ClassName, @{ }); + } + + return ,@($CimData[$ClassName]); + } + + Invoke-IcingaCheckMemory @Arguments; + } $CimData $Counters $Arguments $FailClass); + } + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'writes the used memory, the paging rate and every page file as perfdata' { + Invoke-TestMemoryCheck -Arguments @{ 'Warning' = '80%'; 'Critical' = '90%'; } | Should -Be 0; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + 'memory::ifw_memory::used=12884901888B;13743895347;15461882266;0;17179869184', + 'memory::ifw_memory::pagessec=12.5;;;;', + 'cpagefilesys::ifw_pagefile::used=536870912B;;;0;2147483648', + 'dpagefilesys::ifw_pagefile::used=1048576000B;;;0;1073741824' + ); + } + + It 'renders the used memory with its share of the installed memory' { + Invoke-TestMemoryCheck -Arguments @{ 'Warning' = '70%'; } | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[WARNING] Used Memory: 12GiB (75%) is greater than threshold 11.2GiB (70%)')); + } + + It 'checks the page files and the paging rate against their own thresholds' { + Invoke-TestMemoryCheck -Arguments @{ 'PageFileWarning' = '90%'; 'MemoryPagesSecCritical' = '10'; 'Verbosity' = 2; } | Should -Be 2; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match ([regex]::Escape('[CRITICAL] Memory pages/sec: 12.5 is greater than threshold 10')); + $Output | Should -Match ([regex]::Escape('[OK] C:\pagefile.sys: 512MiB (25%) is ok')); + $Output | Should -Match ([regex]::Escape('[WARNING] D:\pagefile.sys: 1000MiB (97.66%) is greater than threshold 921.6MiB (90%)')); + } + + It 'measures a page file with a configured maximum against that maximum' { + $CimData = New-TestCimData -AutomaticManagedPagefile $false -PageFileSettings @( + [PSCustomObject]@{ 'Name' = 'C:\pagefile.sys'; 'MaximumSize' = [uint32]4096; }, + [PSCustomObject]@{ 'Name' = 'D:\pagefile.sys'; 'MaximumSize' = [uint32]0; } + ); + + Invoke-TestMemoryCheck -CimData $CimData | Should -Be 0; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'cpagefilesys::ifw_pagefile::used=536870912B;;;0;4294967296'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'dpagefilesys::ifw_pagefile::used=1048576000B;;;0;1073741824'; + } + + It 'filters the page files and leaves the package out when none remains' { + Invoke-TestMemoryCheck -Arguments @{ 'ExcludePageFile' = @('D:*'); 'Verbosity' = 2; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Not -Match 'D:\\pagefile'; + + Invoke-TestMemoryCheck -Arguments @{ 'IncludePageFile' = @('X:*'); 'Verbosity' = 2; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Not -Match 'PageFile Usage'; + } + + It 'reports a failed CIM query as UNKNOWN with its reason' { + Invoke-TestMemoryCheck -FailClass 'Win32_ComputerSystem' | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Memory Usage: Simulated failure of Win32_ComputerSystem'; + + Invoke-TestMemoryCheck -FailClass 'Win32_PageFileUsage' | Should -Be 3; + } + + It 'keeps the page files on their allocated size when the settings cannot be read' { + Invoke-TestMemoryCheck -CimData (New-TestCimData -AutomaticManagedPagefile $false) -FailClass 'Win32_PageFileSetting' | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'cpagefilesys::ifw_pagefile::used=536870912B;;;0;2147483648'; + } + + It 'reports unreadable performance counters as UNKNOWN' { + Invoke-TestMemoryCheck -Counters $null | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Memory Usage: Failed to read the performance counters of the category Memory'; + + Invoke-TestMemoryCheck -Counters (New-TestMemoryCounter -Available 'Counter not initialized') | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[UNKNOWN] Used Memory: Failed to read the performance counter \Memory\Available Bytes: Counter not initialized')); + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestMemoryCheck -Arguments @{ 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } +} diff --git a/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 b/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 new file mode 100644 index 0000000..c1a4159 --- /dev/null +++ b/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 @@ -0,0 +1,188 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckPartitionSpace' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Builds a volume entry in the shape of Get-IcingaDiskInformation -Entrypoint 'Volume'. + function New-TestVolume() + { + param ( + [string]$Name = '', + [string]$DriveLetter = '', + [string]$Label = '', + $Capacity = $null, + $FreeSpace = $null + ); + + $UsedSpace = $null; + + if ($null -ne $Capacity -and $null -ne $FreeSpace) { + $UsedSpace = [uint64]$Capacity - [uint64]$FreeSpace; + } + + return @{ + 'DeviceId' = $Name; + 'Name' = $Name; + 'DriveLetter' = $DriveLetter; + 'Label' = $Label; + 'FileSystem' = 'NTFS'; + 'Size' = $Capacity; + 'FreeSpace' = $FreeSpace; + 'UsedSpace' = $UsedSpace; + }; + } + + # Runs the plugin inside the module scope with Get-IcingaDiskInformation + # shadowed by a function, so the check works on the given volume entries. + function Invoke-TestPartitionCheck() + { + param ( + [array]$StubData = @(), + [hashtable]$Arguments = @{ }, + [switch]$Fail = $false + ); + + return (& $script:IcingaModule { + param ($StubData, $Arguments, $Fail); + + function Get-IcingaDiskInformation() + { + param ( + [string]$Entrypoint = 'PhysicalDisk' + ); + + if ($Fail) { + return [IcingaError]::new('Simulated volume failure'); + } + + [hashtable]$Volumes = @{ }; + + foreach ($Volume in $StubData) { + $Volumes[$Volume.DeviceId] = $Volume; + } + + return $Volumes; + } + + Invoke-IcingaCheckPartitionSpace @Arguments; + } $StubData $Arguments $Fail); + } + + # 512GB volume with 442.692GB used (86.46%). + $script:DriveC = New-TestVolume -Name 'C:\' -DriveLetter 'C:' -Label 'System' -Capacity ([uint64]512000000000) -FreeSpace ([uint64]69308000000); + # 100GB volume with 10GB used (10%). + $script:DriveD = New-TestVolume -Name 'D:\' -DriveLetter 'D:' -Label 'Data' -Capacity ([uint64]100000000000) -FreeSpace ([uint64]90000000000); + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + Context 'Used space' { + It 'evaluates the used space against percent thresholds' { + Invoke-TestPartitionCheck -StubData @($script:DriveC, $script:DriveD) -Arguments @{ 'Warning' = '80%'; 'Critical' = '90%'; } | Should -Be 1; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match '^\[WARNING\] Used Partition Space: 1 Warning 1 Ok'; + $Result.Output | Should -Match ([regex]::Escape('[WARNING] Partition C: 412.29GiB (86.46%) is greater than threshold 381.47GiB (80%)')); + } + + It 'writes the used space and resolved thresholds in bytes into the perfdata' { + Invoke-TestPartitionCheck -StubData @($script:DriveC, $script:DriveD) -Arguments @{ 'Warning' = '80%'; 'Critical' = '90%'; } | Out-Null; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + 'c::ifw_partitionspace::used=442692000000B;409600000000;460800000000;0;512000000000', + 'd::ifw_partitionspace::used=10000000000B;80000000000;90000000000;0;100000000000' + ); + } + + It 'accepts absolute size thresholds' { + Invoke-TestPartitionCheck -StubData @($script:DriveC) -Arguments @{ 'Warning' = '400GB'; 'Critical' = '450GB'; 'Verbosity' = 2; } | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('Partition C: 412.29GiB is greater than threshold 400GB')); + } + } + + Context 'Free space' { + It 'evaluates the free space against a percent range with CheckFreeSpace' { + Invoke-TestPartitionCheck -StubData @($script:DriveC) -Arguments @{ 'CheckFreeSpace' = $true; 'Warning' = '15%:'; 'Critical' = '5%:'; } | Should -Be 1; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match '^\[WARNING\] Free Partition Space'; + $Result.Output | Should -Match ([regex]::Escape('Partition C: 64.55GiB (13.54%) is lower than threshold 71.53GiB (15%)')); + $Result.PerformanceData | Should -Be @('c::ifw_partitionspace::free=69308000000B;76800000000:;25600000000:;0;512000000000'); + } + } + + Context 'Partition selection' { + It 'only checks included partitions, ignoring the drive letter colon' { + Invoke-TestPartitionCheck -StubData @($script:DriveC, $script:DriveD) -Arguments @{ 'Include' = 'D:'; 'Warning' = '80%'; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @('d::ifw_partitionspace::used=10000000000B;80000000000;;0;100000000000'); + } + + It 'skips excluded partitions' { + Invoke-TestPartitionCheck -StubData @($script:DriveC, $script:DriveD) -Arguments @{ 'Exclude' = 'C:\'; 'Warning' = '80%'; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 1; + } + + It 'names a volume without drive letter after its label, or its path without a label' { + $Labeled = New-TestVolume -Name '\\?\Volume{1}\' -Label 'Recovery' -Capacity ([uint64]1000000000) -FreeSpace ([uint64]500000000); + $Unlabeled = New-TestVolume -Name '\\?\Volume{2}\' -Capacity ([uint64]1000000000) -FreeSpace ([uint64]500000000); + + Invoke-TestPartitionCheck -StubData @($Labeled, $Unlabeled) -Arguments @{ 'Verbosity' = 2; } | Should -Be 0; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('[OK] Partition Recovery: ')); + $Result.Output | Should -Match ([regex]::Escape('[OK] Partition \\?\Volume{2}\: ')); + $Result.PerformanceData | Should -Contain 'recovery::ifw_partitionspace::used=500000000B;;;0;1000000000'; + $Result.PerformanceData | Should -Contain 'volume2::ifw_partitionspace::used=500000000B;;;0;1000000000'; + } + + It 'reports a missing required partition as CRITICAL' { + Invoke-TestPartitionCheck -StubData @($script:DriveD) -Arguments @{ 'RequiredPartition' = 'D:', 'E:'; } | Should -Be 2; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('[CRITICAL] Partition E: Mandatory partition not found on host')); + $Result.Output | Should -Not -Match 'Partition D: Mandatory'; + } + + It 'returns UNKNOWN when no partition matches, OK with IgnoreEmptyChecks' { + Invoke-TestPartitionCheck -StubData @($script:DriveC) -Arguments @{ 'Include' = 'Q'; } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Used Partition Space: No partition matches the given filter'; + + Invoke-TestPartitionCheck -StubData @($script:DriveC) -Arguments @{ 'Include' = 'Q'; 'IgnoreEmptyChecks' = $true; } | Should -Be 0; + } + } + + Context 'Missing size data and errors' { + It 'reports a volume without size as UNKNOWN, OK with SkipUnknown' { + $NoSize = New-TestVolume -Name 'F:\' -DriveLetter 'F:'; + + Invoke-TestPartitionCheck -StubData @($NoSize) -Arguments @{ 'Warning' = '80%'; } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[UNKNOWN] Partition F: No partition size available')); + + Invoke-TestPartitionCheck -StubData @($NoSize) -Arguments @{ 'Warning' = '80%'; 'SkipUnknown' = $true; } | Should -Be 0; + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestPartitionCheck -StubData @($script:DriveC) -Arguments @{ 'Warning' = '80%'; 'NoPerfData' = $true; } | Should -Be 1; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } + + It 'returns UNKNOWN when the volume query fails' { + Invoke-TestPartitionCheck -Fail | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Used Partition Space: Simulated volume failure'; + } + } +} diff --git a/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 b/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 new file mode 100644 index 0000000..e870f03 --- /dev/null +++ b/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 @@ -0,0 +1,194 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckPerfCounter' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Builds one counter result in the shape of Get-IcingaPerformanceCounter. A + # string value becomes the counter error. + function New-TestLeaf() + { + param ( + $Value = [decimal]0, + [string]$Type = '' + ); + + $Leaf = @{ 'value' = [decimal]0; 'sample' = $null; 'help' = ''; 'type' = $Type; 'error' = $null; }; + + if ($Value -is [string]) { + $Leaf['error'] = $Value; + } else { + $Leaf['value'] = [decimal]$Value; + } + + return $Leaf; + } + + # Runs the plugin inside the module scope with Get-IcingaPerformanceCounter + # shadowed, so the check works on the given counter results. + function Invoke-TestPerfCounterCheck() + { + param ( + $StubData = $null, + [hashtable]$Arguments = @{ } + ); + + return (& $script:IcingaModule { + param ($StubData, $Arguments); + + function Get-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @(), + [int]$TimeoutMs = 5000, + [switch]$StructureByInstance = $false + ); + + return $StubData; + } + + Invoke-IcingaCheckPerfCounter @Arguments; + } $StubData $Arguments); + } + + $script:Counters = @{ + '\Processor(*)\% Processor Time' = @{ + '\Processor(1)\% Processor Time' = (New-TestLeaf -Value 95 -Type 'Timer100NsInverse'); + '\Processor(0)\% Processor Time' = (New-TestLeaf -Value 10 -Type 'Timer100NsInverse'); + '\Processor(_Total)\% Processor Time' = (New-TestLeaf -Value 52.5 -Type 'Timer100NsInverse'); + }; + '\Memory\Available Bytes' = (New-TestLeaf -Value 50 -Type 'NumberOfItems64'); + '\Nope\Nothing' = (New-TestLeaf -Value "Category 'Nope' does not exist."); + '\Disk(*)\Reads' = @{ }; + '\Broken(*)\Value' = @{ + '\Broken(a)\Value' = (New-TestLeaf -Value 'Counter not initialized'); + '\Broken(b)\Value' = (New-TestLeaf -Value 'Instance vanished'); + }; + }; + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'writes one metric per instance with the category as index' { + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Processor(*)\% Processor Time', '\Memory\Available Bytes'); 'Warning' = '80'; 'Critical' = '90'; } | Should -Be 2; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + 'processor::ifw_perfcounter::percentprocessortime0=10%;80;90;;', + 'processor::ifw_perfcounter::percentprocessortime1=95%;80;90;;', + 'processor::ifw_perfcounter::percentprocessortime_total=52.5%;80;90;;', + 'memory::ifw_perfcounter::availablebytes=50B;80;90;;' + ); + } + + It 'groups the instances into one package per requested counter' { + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Processor(*)\% Processor Time', '\Memory\Available Bytes'); 'Critical' = '90'; 'Verbosity' = 2; } | Should -Be 2; + + [array]$Lines = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n"; + $Lines[0] | Should -Be '[CRITICAL] Performance Counter: 1 Critical 3 Ok [CRITICAL] \Processor(1)\% Processor Time'; + $Lines[1] | Should -Be '\_ [CRITICAL] \Processor(*)\% Processor Time'; + $Lines[3] | Should -Be ' \_ [CRITICAL] \Processor(1)\% Processor Time: 95% is greater than threshold 90%'; + $Lines[5] | Should -Be '\_ [OK] \Memory\Available Bytes'; + } + + It 'filters the instances with ExcludeCounter and IncludeCounter' { + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Processor(*)\% Processor Time'); 'ExcludeCounter' = @('*_Total*'); } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 2; + + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Processor(*)\% Processor Time'); 'IncludeCounter' = @('*(0)*'); } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @('processor::ifw_perfcounter::percentprocessortime0=10%;;;;'); + } + + It 'derives the unit of every value from the counter type and name' { + $Units = @{ + '\Memory\Available MBytes' = (New-TestLeaf -Value 2 -Type 'NumberOfItems64'); + '\PhysicalDisk(_Total)\Avg. Disk sec/Read' = (New-TestLeaf -Value 0.004 -Type 'AverageTimer32'); + '\System\System Up Time' = (New-TestLeaf -Value 93784.33 -Type 'ElapsedTime'); + '\Memory\Pages/sec' = (New-TestLeaf -Value 12.5 -Type 'RateOfCountsPerSecond32'); + '\PhysicalDisk(_Total)\% Disk Time' = (New-TestLeaf -Value 7.456789 -Type '542573824'); + '\PhysicalDisk(_Total)\Disk Bytes/sec' = (New-TestLeaf -Value 1048576.4 -Type 'RateOfCountsPerSecond64'); + }; + + Invoke-TestPerfCounterCheck -StubData $Units -Arguments @{ 'PerfCounter' = @($Units.Keys); 'Verbosity' = 2; } | Should -Be 0; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('\Memory\Available MBytes: 2MiB is ok')); + $Result.Output | Should -Match ([regex]::Escape('\Avg. Disk sec/Read: 4ms is ok')); + $Result.Output | Should -Match ([regex]::Escape('\System\System Up Time: 1d 2h 3m 4s is ok')); + $Result.Output | Should -Match ([regex]::Escape('\Memory\Pages/sec: 12.5 is ok')); + $Result.Output | Should -Match ([regex]::Escape('\% Disk Time: 7.46% is ok')); + $Result.Output | Should -Match ([regex]::Escape('\Disk Bytes/sec: 1MiB is ok')); + $Result.PerformanceData | Should -Contain 'memory::ifw_perfcounter::availablembytes=2097152B;;;;'; + $Result.PerformanceData | Should -Contain 'system::ifw_perfcounter::systemuptime=93784s;;;;'; + $Result.PerformanceData | Should -Contain 'memory::ifw_perfcounter::pagessec=12.5;;;;'; + + # Three counters of the same category and instance keep distinct labels. + $Result.PerformanceData | Should -Contain 'physicaldisk::ifw_perfcounter::avgdisksecread_total=0.004s;;;;'; + $Result.PerformanceData | Should -Contain 'physicaldisk::ifw_perfcounter::percentdisktime_total=7.46%;;;;'; + $Result.PerformanceData | Should -Contain 'physicaldisk::ifw_perfcounter::diskbytessec_total=1048576B;;;;'; + } + + It 'compares sizes and durations against thresholds with units' { + $Units = @{ + '\Memory\Available MBytes' = (New-TestLeaf -Value 2 -Type 'NumberOfItems64'); + '\System\System Up Time' = (New-TestLeaf -Value 93784 -Type 'ElapsedTime'); + }; + + Invoke-TestPerfCounterCheck -StubData $Units -Arguments @{ 'PerfCounter' = @('\Memory\Available MBytes'); 'Warning' = '1MB'; } | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('2MiB is greater than threshold 1MB')); + + Invoke-TestPerfCounterCheck -StubData $Units -Arguments @{ 'PerfCounter' = @('\System\System Up Time'); 'Critical' = '1d'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('1d 2h 3m 4s is greater than threshold 1d')); + } + + It 'reports a failed concrete counter as UNKNOWN with its error' { + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Memory\Available Bytes', '\Nope\Nothing'); } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape("[UNKNOWN] \Nope\Nothing: Failed to read the performance counter: Category 'Nope' does not exist.")); + } + + It 'reports a wildcard counter without readable instances as UNKNOWN with the first error' { + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Disk(*)\Reads', '\Broken(*)\Value'); } | Should -Be 3; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match ([regex]::Escape('[UNKNOWN] \Disk(*)\Reads: Failed to read the performance counter: no instance of this counter exists')); + $Output | Should -Match ([regex]::Escape('[UNKNOWN] \Broken(*)\Value: Failed to read the performance counter: Counter not initialized')); + } + + It 'reports an empty result as UNKNOWN, or OK with IgnoreEmptyChecks' { + [hashtable]$Arguments = @{ 'PerfCounter' = @('\Processor(*)\% Processor Time'); 'IncludeCounter' = @('*(9)*'); }; + + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments $Arguments | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Performance Counter: No performance counter matches the given filter'; + + $Arguments['IgnoreEmptyChecks'] = $true; + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments $Arguments | Should -Be 0; + } + + It 'rejects a missing or invalid counter path and a timed out read' { + Invoke-TestPerfCounterCheck -StubData $script:Counters | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Performance Counter: No performance counter was provided'; + + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('Memory'); } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[UNKNOWN] Memory: Invalid performance counter path')); + + Invoke-TestPerfCounterCheck -StubData $null -Arguments @{ 'PerfCounter' = @('\Memory\Available Bytes'); } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Performance Counter: Failed to read the performance counters \Memory\Available Bytes'; + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Memory\Available Bytes'); 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } +} diff --git a/Tests/Invoke-IcingaCheckService.Tests.ps1 b/Tests/Invoke-IcingaCheckService.Tests.ps1 new file mode 100644 index 0000000..b53b89e --- /dev/null +++ b/Tests/Invoke-IcingaCheckService.Tests.ps1 @@ -0,0 +1,212 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckService' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + function New-TestService() + { + param ( + [string]$Name = '', + [string]$DisplayName = '', + [string]$State = 'Running', + [string]$StartMode = 'Auto', + [int]$ExitCode = 0 + ); + + return [PSCustomObject]@{ + 'Name' = $Name; + 'DisplayName' = $DisplayName; + 'State' = $State; + 'StartMode' = $StartMode; + 'ExitCode' = $ExitCode; + }; + } + + # Runs the plugin inside the module scope with Get-CimInstance shadowed by a + # function, so the check works on the given service objects instead of CIM. + function Invoke-TestServiceCheck() + { + param ( + [array]$StubData = @(), + [hashtable]$Arguments = @{ }, + [switch]$Fail = $false + ); + + return (& $script:IcingaModule { + param ($StubData, $Arguments, $Fail); + + function Get-CimInstance() + { + [CmdletBinding()] + param ( + [string]$ClassName = '', + [string]$Namespace = '', + [string]$Filter = '', + [string[]]$Property = @() + ); + + if ($Fail) { + throw 'Access is denied'; + } + + return $StubData; + } + + Invoke-IcingaCheckService @Arguments; + } $StubData $Arguments $Fail); + } + + $script:Spooler = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler'; + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + Context 'Explicit services' { + It 'reports a running service as OK with state and summary perfdata' { + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Spooler'; 'Verbosity' = 2; } | Should -Be 0; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('[OK] Service "Print Spooler (Spooler)": ''Running'' is ok')); + $Result.PerformanceData | Should -Contain 'spooler::ifw_service::state=4;;;;'; + $Result.PerformanceData | Should -Contain 'summary::ifw_service::running=1;;;;'; + $Result.PerformanceData | Should -Contain 'summary::ifw_service::count=1;;;;'; + } + + It 'reports a stopped service as CRITICAL by default' { + $Stopped = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler' -State 'Stopped'; + + Invoke-TestServiceCheck -StubData @($Stopped) -Arguments @{ 'Service' = 'Spooler'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[CRITICAL] Service "Print Spooler (Spooler)": ''Stopped'' does not equal pattern ''Running''')); + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'spooler::ifw_service::state=1;;;;'; + } + + It 'applies OverrideNotOk to a service in the wrong state' { + $Stopped = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler' -State 'Stopped'; + + Invoke-TestServiceCheck -StubData @($Stopped) -Arguments @{ 'Service' = 'Spooler'; 'OverrideNotOk' = 'Warning'; } | Should -Be 1; + Invoke-TestServiceCheck -StubData @($Stopped) -Arguments @{ 'Service' = 'Spooler'; 'OverrideNotOk' = 'Unknown'; } | Should -Be 3; + Invoke-TestServiceCheck -StubData @($Stopped) -Arguments @{ 'Service' = 'Spooler'; 'OverrideNotOk' = 'Ok'; } | Should -Be 0; + } + + It 'compares against the expected Status' { + $Stopped = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler' -State 'Stopped'; + + Invoke-TestServiceCheck -StubData @($Stopped) -Arguments @{ 'Service' = 'Spooler'; 'Status' = 'Stopped'; } | Should -Be 0; + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Spooler'; 'Status' = 'Stopped'; } | Should -Be 2; + } + + It 'maps pending states to their status code and summary counter' { + $Pending = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler' -State 'Start Pending'; + + Invoke-TestServiceCheck -StubData @($Pending) -Arguments @{ 'Service' = 'Spooler'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'spooler::ifw_service::state=2;;;;'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'summary::ifw_service::pendingstarted=1;;;;'; + } + + It 'reports a service in the Unknown state with state code 0' { + $Unknown = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler' -State 'Unknown'; + + Invoke-TestServiceCheck -StubData @($Unknown) -Arguments @{ 'Service' = 'Spooler'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'spooler::ifw_service::state=0;;;;'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'summary::ifw_service::count=1;;;;'; + } + + It 'rejects a Status that is no IcingaServiceStatus' { + { Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Spooler'; 'Status' = 'Sleeping'; } } | Should -Throw; + } + + It 'selects services by wildcard and honours Exclude' { + $Services = @( + (New-TestService -Name 'WinRM' -DisplayName 'Windows Remote Management'), + (New-TestService -Name 'WinDefend' -DisplayName 'Microsoft Defender Antivirus Service'), + $script:Spooler + ); + + Invoke-TestServiceCheck -StubData $Services -Arguments @{ 'Service' = 'Win*'; 'Exclude' = 'WinDefend'; } | Should -Be 0; + + [array]$StateMetrics = @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Where-Object { $_ -like '*::state=*' }); + $StateMetrics | Should -Be @('winrm::ifw_service::state=4;;;;'); + } + + It 'matches services by display name' { + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Print Spooler'; 'Verbosity' = 2; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Not -Match 'Service not found'; + } + + It 'only checks services with a matching startup type' { + $Services = @( + (New-TestService -Name 'Manual1' -DisplayName 'Manual One' -State 'Stopped' -StartMode 'Manual'), + (New-TestService -Name 'Auto1' -DisplayName 'Auto One' -State 'Running' -StartMode 'Auto') + ); + + Invoke-TestServiceCheck -StubData $Services -Arguments @{ 'Service' = '*'; 'Status' = 'Stopped'; 'FilterStartupType' = 'Manual'; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'summary::ifw_service::count=1;;;;'; + } + } + + Context 'Missing services' { + It 'reports a service that does not exist as UNKNOWN' { + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Spooler', 'DoesNotExist'; } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[UNKNOWN] DoesNotExist: Service not found')); + } + + It 'applies OverrideNotFound to a service that does not exist' { + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'DoesNotExist'; 'OverrideNotFound' = 'Critical'; } | Should -Be 2; + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'DoesNotExist'; 'OverrideNotFound' = 'Ok'; } | Should -Be 0; + } + + It 'returns UNKNOWN when a wildcard matches nothing, OK with MitigateUnknown' { + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Nope*'; } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Services: No service matches the given filter'; + + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Nope*'; 'MitigateUnknown' = $true; } | Should -Be 0; + } + } + + Context 'Automatic services' { + It 'checks only automatic services and accepts a clean exit' { + $Services = @( + (New-TestService -Name 'AutoRunning' -DisplayName 'Auto Running'), + (New-TestService -Name 'AutoDone' -DisplayName 'Auto Done' -State 'Stopped' -ExitCode 0), + (New-TestService -Name 'AutoFailed' -DisplayName 'Auto Failed' -State 'Stopped' -ExitCode 1067), + (New-TestService -Name 'ManualStopped' -DisplayName 'Manual Stopped' -State 'Stopped' -StartMode 'Manual' -ExitCode 1) + ); + + Invoke-TestServiceCheck -StubData $Services | Should -Be 2; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match '^\[CRITICAL\] Services: 1 Critical 2 Ok'; + $Result.Output | Should -Match ([regex]::Escape('Service "Auto Failed (AutoFailed)"')); + $Result.Output | Should -Not -Match 'ManualStopped'; + $Result.PerformanceData | Should -Contain 'summary::ifw_service::count=3;;;;'; + $Result.PerformanceData | Should -Contain 'summary::ifw_service::stopped=2;;;;'; + @($Result.PerformanceData | Where-Object { $_ -like '*::state=*' }).Count | Should -Be 0; + } + } + + Context 'Errors and perfdata switches' { + It 'suppresses all performance data with NoPerfData' { + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Spooler'; 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } + + It 'returns UNKNOWN when the service query fails' { + Invoke-TestServiceCheck -Fail -Arguments @{ 'Service' = 'Spooler'; } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Services: The CIM query failed with an unhandled error: Class "Win32_Service", Namespace "root/cimv2": Access is denied'; + } + } +} diff --git a/Tests/Invoke-IcingaCheckUptime.Tests.ps1 b/Tests/Invoke-IcingaCheckUptime.Tests.ps1 new file mode 100644 index 0000000..9dae030 --- /dev/null +++ b/Tests/Invoke-IcingaCheckUptime.Tests.ps1 @@ -0,0 +1,108 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckUptime' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Builds the -StructureByInstance result of '\System\System Up Time'. A string + # value becomes the counter error. + function New-TestUptimeCounter() + { + param ( + $Value = [decimal]0 + ); + + $Leaf = @{ 'value' = [decimal]0; 'sample' = $null; 'help' = ''; 'type' = ''; 'error' = $null; }; + + if ($Value -is [string]) { + $Leaf['error'] = $Value; + } else { + $Leaf['value'] = [decimal]$Value; + } + + return @{ 'System' = @{ 'System Up Time' = $Leaf; }; }; + } + + # Runs the plugin inside the module scope with the performance counter + # functions shadowed, so the check works on the given counter value. + function Invoke-TestUptimeCheck() + { + param ( + $StubData = $null, + [hashtable]$Arguments = @{ } + ); + + return (& $script:IcingaModule { + param ($StubData, $Arguments); + + function New-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @() + ); + } + + function Get-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @(), + [int]$TimeoutMs = 5000, + [switch]$StructureByInstance = $false + ); + + return $StubData; + } + + Invoke-IcingaCheckUptime @Arguments; + } $StubData $Arguments); + } + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'shows the uptime as duration and writes it in whole seconds' { + Invoke-TestUptimeCheck -StubData (New-TestUptimeCounter -Value 93784.4) -Arguments @{ 'Warning' = '1d:'; 'Verbosity' = 2; } | Should -Be 0; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + [array]$Lines = $Result.Output -split "`n"; + $Lines[0] | Should -Be '[OK] System Uptime: 1d 2h 3m 4s: 2 Ok'; + $Lines[1] | Should -Be '\_ [OK] System Uptime: 1d 2h 3m 4s is ok'; + $Lines[2] | Should -Match '^\\_ \[INFO\] Last Boot: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$'; + $Result.PerformanceData | Should -Be @('windows::ifw_uptime::uptime=93784s;86400:;;;'); + } + + It 'raises the state after a recent restart' { + Invoke-TestUptimeCheck -StubData (New-TestUptimeCounter -Value 3600) -Arguments @{ 'Warning' = '1d:'; 'Critical' = '30m:'; } | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[WARNING] System Uptime: 1h is lower than threshold 1d')); + } + + It 'raises the state when the system runs longer than allowed' { + Invoke-TestUptimeCheck -StubData (New-TestUptimeCounter -Value 5184000) -Arguments @{ 'Critical' = '30d'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[CRITICAL] System Uptime: 2M is greater than threshold 30d')); + } + + It 'reports a failed counter read as UNKNOWN' { + Invoke-TestUptimeCheck -StubData (New-TestUptimeCounter -Value 'Counter not initialized') | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] System Uptime: Failed to read the performance counter \System\System Up Time: Counter not initialized'; + + Invoke-TestUptimeCheck -StubData $null | Should -Be 3; + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestUptimeCheck -StubData (New-TestUptimeCounter -Value 3600) -Arguments @{ 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } +} diff --git a/Tests/Test-IcingaArrayFilter.Tests.ps1 b/Tests/Test-IcingaArrayFilter.Tests.ps1 new file mode 100644 index 0000000..dfe76f0 --- /dev/null +++ b/Tests/Test-IcingaArrayFilter.Tests.ps1 @@ -0,0 +1,58 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Test-IcingaArrayFilter' { + Context 'Single values' { + It 'passes every value without filters' { + Test-IcingaArrayFilter -InputObject 'Spooler' | Should -BeTrue; + } + + It 'requires an include match when an include list is given' { + Test-IcingaArrayFilter -InputObject 'Spooler' -Include 'Spo*' | Should -BeTrue; + Test-IcingaArrayFilter -InputObject 'Spooler' -Include 'WinRM', 'W*' | Should -BeFalse; + } + + It 'matches case-insensitively with ? and [] wildcards' { + Test-IcingaArrayFilter -InputObject 'SPOOLER' -Include 'spo?ler' | Should -BeTrue; + Test-IcingaArrayFilter -InputObject 'D' -Include '[c-e]' | Should -BeTrue; + } + + It 'lets an exclude match win over an include match' { + Test-IcingaArrayFilter -InputObject 'Spooler' -Include '*' -Exclude 'Spooler' | Should -BeFalse; + Test-IcingaArrayFilter -InputObject 'WinRM' -Exclude 'Spooler' | Should -BeTrue; + } + + It 'compares non-string values by their string form' { + Test-IcingaArrayFilter -InputObject 4 -Include '4' | Should -BeTrue; + } + + It 'never passes $null' { + Test-IcingaArrayFilter -InputObject $null | Should -BeFalse; + } + + It 'treats an invalid wildcard pattern as no match instead of throwing' { + Test-IcingaArrayFilter -InputObject 'abc' -Include '[abc' | Should -BeFalse; + Test-IcingaArrayFilter -InputObject 'abc' -Exclude '[abc' | Should -BeTrue; + } + } + + Context 'Arrays' { + It 'returns the passing elements as an array' { + $Result = Test-IcingaArrayFilter -InputObject @('C', 'D', 'E') -Exclude 'D'; + ($Result -is [array]) | Should -BeTrue; + $Result | Should -Be @('C', 'E'); + } + + It 'returns an array for a single passing element and an empty array for none' { + $Single = Test-IcingaArrayFilter -InputObject @('C', 'D') -Include 'C'; + ($Single -is [array]) | Should -BeTrue; + $Single.Count | Should -Be 1; + + $None = Test-IcingaArrayFilter -InputObject @('C', 'D') -Include 'Q'; + ($None -is [array]) | Should -BeTrue; + $None.Count | Should -Be 0; + } + } +} diff --git a/build/Build-ModuleProject.ps1 b/build/Build-ModuleProject.ps1 index 374ef4c..c7a1d7d 100644 --- a/build/Build-ModuleProject.ps1 +++ b/build/Build-ModuleProject.ps1 @@ -192,6 +192,13 @@ if (Test-Path $OutputPath) { Write-Host " * Output directory ready: $OutputPath" -ForegroundColor Green; +# TODO: Compile native helpers into signed DLLs here instead of generating them at runtime. +# Keep their C# sources as .cs files in the repository (e.g. the DeviceIoControl based +# volume/disk-extent and NTFS volume data reader for Get-IcingaDiskInformation), build +# them into lib/ during this step, sign them together with the module and load them at +# import time only when the type is not present yet. Nothing may call Add-Type with a +# type definition at runtime anymore. + # Build consolidated classes and kernel files Write-Host "`n[3/4] Building consolidated classes and kernel modules..." -ForegroundColor Yellow; diff --git a/src/Classes/DataTypes/IcingaServiceStartupType.ps1 b/src/Classes/DataTypes/IcingaServiceStartupType.ps1 new file mode 100644 index 0000000..96405a9 --- /dev/null +++ b/src/Classes/DataTypes/IcingaServiceStartupType.ps1 @@ -0,0 +1,107 @@ +<# +.SYNOPSIS +Startup type of a Windows service + +.DESCRIPTION +IcingaServiceStartupType lists the ways a Windows service can be started. The +numeric values 0 to 4 match System.ServiceProcess.ServiceStartMode (Boot, +System, Automatic, Manual, Disabled); Unknown (5) covers services whose start +mode cannot be determined. + +The enum is used directly as a parameter type, so a plugin parameter such as +[IcingaServiceStartupType[]]$FilterStartupType accepts 'Automatic', 'manual' or +3 and rejects anything else with the list of valid names. + +.OUTPUTS +IcingaServiceStartupType — Enum value of the service startup type. + +.EXAMPLE +PS> [IcingaServiceStartupType]'Manual' + +Converts the name into IcingaServiceStartupType::Manual. + +.NOTES +Defined in the kernel ahead of every function, so functions may use it as a +parameter type. Not visible outside the module scope; callers pass the name or +code as a string. +#> +enum IcingaServiceStartupType +{ + Boot = 0; + System = 1; + Automatic = 2; + Manual = 3; + Disabled = 4; + Unknown = 5; +} + +<# +.SYNOPSIS +Map external service start mode values onto IcingaServiceStartupType + +.DESCRIPTION +IcingaServiceStartupTypeMap converts the start mode representations of the +different Windows service sources into an IcingaServiceStartupType: the +Win32_Service 'StartMode' strings (which report automatic services as 'Auto'), +the ServiceStartMode values of Get-Service, enum names in any casing and numeric +codes. Every value that cannot be mapped resolves to Unknown instead of +throwing. + +.OUTPUTS +IcingaServiceStartupTypeMap — Static helper class, not meant to be instantiated. + +.EXAMPLE +PS> [IcingaServiceStartupTypeMap]::Resolve('Auto') + +Returns IcingaServiceStartupType::Automatic. + +.NOTES +Pure conversion helper without state or external dependencies. +#> +class IcingaServiceStartupTypeMap +{ + <# + .SYNOPSIS + Resolve a service start mode value into an IcingaServiceStartupType + + .DESCRIPTION + Removes blanks from the value, translates the Win32_Service 'Auto' start mode + to Automatic and converts the rest by name (case-insensitive) or numeric code. + Returns Unknown for $null, empty, unknown names and undefined codes. + + .PARAMETER Value + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------------------------------|---------| + | Value | System.Object | Startup type name, Win32_Service start mode, ServiceStartMode or code. | | + + .OUTPUTS + IcingaServiceStartupType — The resolved startup type, Unknown when it cannot be mapped. + + .EXAMPLE + PS> [IcingaServiceStartupTypeMap]::Resolve('Disabled') + + .NOTES + PowerShell enum conversion rejects undefined codes, so '-as' returns $null for + them and they fall back to Unknown like unknown names. + #> + static [IcingaServiceStartupType] Resolve([object]$Value) + { + if ($null -eq $Value) { + return [IcingaServiceStartupType]::Unknown; + } + + [string]$Name = ([string]$Value).Replace(' ', ''); + + if ($Name -eq 'Auto') { + return [IcingaServiceStartupType]::Automatic; + } + + $StartupType = $Name -as [IcingaServiceStartupType]; + + if ($null -eq $StartupType) { + return [IcingaServiceStartupType]::Unknown; + } + + return $StartupType; + } +} diff --git a/src/Classes/DataTypes/IcingaServiceStatus.ps1 b/src/Classes/DataTypes/IcingaServiceStatus.ps1 new file mode 100644 index 0000000..8687fd1 --- /dev/null +++ b/src/Classes/DataTypes/IcingaServiceStatus.ps1 @@ -0,0 +1,105 @@ +<# +.SYNOPSIS +Status of a Windows service with its numeric status code + +.DESCRIPTION +IcingaServiceStatus lists every state a Windows service can be in. The numeric +values match System.ServiceProcess.ServiceControllerStatus (1 Stopped to 7 +Paused) and are written as the service state performance data. Unknown (0) +covers services whose state cannot be determined, which Win32_Service reports +as 'Unknown'. + +The enum is used directly as a parameter type, so a plugin parameter such as +[IcingaServiceStatus]$Status accepts 'Running', 'running' or 4 and rejects +anything else with the list of valid names. A value converts to its code with +[int] and to its name with [string]. + +.OUTPUTS +IcingaServiceStatus — Enum value of the service status. + +.EXAMPLE +PS> [int][IcingaServiceStatus]::Running + +Returns 4, the code used for the service state performance data. + +.NOTES +Defined in the kernel ahead of every function, so functions may use it as a +parameter type. Not visible outside the module scope; callers pass the name or +code as a string. +#> +enum IcingaServiceStatus +{ + Unknown = 0; + Stopped = 1; + StartPending = 2; + StopPending = 3; + Running = 4; + ContinuePending = 5; + PausePending = 6; + Paused = 7; +} + +<# +.SYNOPSIS +Map external service status values onto IcingaServiceStatus + +.DESCRIPTION +IcingaServiceStatusMap converts the status representations of the different +Windows service sources into an IcingaServiceStatus: the Win32_Service 'State' +strings with blanks ('Start Pending'), the ServiceControllerStatus values of +Get-Service, enum names in any casing and numeric status codes. Every value that +cannot be mapped resolves to Unknown instead of throwing, so a plugin can always +report a state. + +.OUTPUTS +IcingaServiceStatusMap — Static helper class, not meant to be instantiated. + +.EXAMPLE +PS> [IcingaServiceStatusMap]::Resolve('Start Pending') + +Returns IcingaServiceStatus::StartPending. + +.NOTES +Pure conversion helper without state or external dependencies. +#> +class IcingaServiceStatusMap +{ + <# + .SYNOPSIS + Resolve a service status value into an IcingaServiceStatus + + .DESCRIPTION + Removes blanks from the value and converts it into an IcingaServiceStatus by + name (case-insensitive) or by numeric code. Returns Unknown for $null, empty, + unknown names and undefined codes. + + .PARAMETER Value + | Name | Type | Description | Default | + |-------|---------------|----------------------------------------------------------------|---------| + | Value | System.Object | Status name, Win32_Service state, ServiceControllerStatus or code. | | + + .OUTPUTS + IcingaServiceStatus — The resolved status, Unknown when it cannot be mapped. + + .EXAMPLE + PS> [IcingaServiceStatusMap]::Resolve('Running') + + .NOTES + PowerShell enum conversion rejects undefined codes, so '-as' returns $null for + them and they fall back to Unknown like unknown names. + #> + static [IcingaServiceStatus] Resolve([object]$Value) + { + if ($null -eq $Value) { + return [IcingaServiceStatus]::Unknown; + } + + $Status = ([string]$Value).Replace(' ', '') -as [IcingaServiceStatus]; + + if ($null -eq $Status) { + return [IcingaServiceStatus]::Unknown; + } + + return $Status; + } +} diff --git a/src/Classes/Tools/IcingaSortKey.ps1 b/src/Classes/Tools/IcingaSortKey.ps1 new file mode 100644 index 0000000..160896d --- /dev/null +++ b/src/Classes/Tools/IcingaSortKey.ps1 @@ -0,0 +1,169 @@ +<# +.SYNOPSIS +Build ordinal sort keys that reproduce a natural, multi-property sort order + +.DESCRIPTION +IcingaSortKey turns objects into strings whose plain ordinal order equals the +natural order of their properties, so ConvertTo-IcingaSortedArray can sort with +the native [Array]::Sort and StringComparer.Ordinal instead of running +PowerShell code (or a script block) for every comparison. + +A string value becomes its upper-case form with every digit run replaced by its +length (three digits) followed by the digits without leading zeros, so '0,2' +sorts before '0,10' and 'Core 9' before 'Core 10'; non-digit characters such as +'_' sort after digits, which puts instance names like '_Total' behind the +numbered ones. A numeric value becomes a fixed-point string, so numbers sort +numerically, including decimals and negative values. $null becomes an empty key +and sorts first. Several properties are joined with a separator that sorts below +every other character, so the next property only breaks ties of the previous one. + +.OUTPUTS +IcingaSortKey — Static helper class, not meant to be instantiated. + +.EXAMPLE +PS> [IcingaSortKey]::FromObject($Volume, [string[]]@('Name')) + +Returns the sort key of the volume's Name property. + +.NOTES +Pure helper without state or external dependencies. Numbers are supported +within +/- 1E20. +#> +class IcingaSortKey +{ + static [string]$Separator = [string][char]1; + + <# + .SYNOPSIS + Build the sort key of an object for the given properties + + .DESCRIPTION + Joins the keys of the given properties in order of precedence, or returns + the key of the object itself when no property is given. Hashtables are read + by key, every other object (including CIM instances) by member name. + + .PARAMETER InputObject + | Name | Type | Description | Default | + |-------------|---------------|---------------------------|---------| + | InputObject | System.Object | The object to build for. | | + + .PARAMETER Property + | Name | Type | Description | Default | + |----------|-----------------|---------------------------------------------------|---------| + | Property | System.String[] | Properties in order of precedence; empty uses the object. | | + + .OUTPUTS + System.String — The sort key. + + .EXAMPLE + PS> [IcingaSortKey]::FromObject($Partition, [string[]]@('DiskNumber', 'PartitionNumber')) + + .NOTES + Missing members read as $null and therefore sort first. + #> + static [string] FromObject([object]$InputObject, [string[]]$Property) + { + if ($null -eq $Property -or $Property.Count -eq 0) { + return [IcingaSortKey]::FromValue($InputObject); + } + + [string[]]$Keys = @(); + + foreach ($Name in $Property) { + $Keys += [IcingaSortKey]::FromValue([IcingaSortKey]::GetMemberValue($InputObject, $Name)); + } + + return ($Keys -join [IcingaSortKey]::Separator); + } + + <# + .SYNOPSIS + Build the sort key of a single value + + .DESCRIPTION + Returns an empty key for $null, a fixed-point key for numeric types and the + natural string key for everything else. + + .PARAMETER Value + | Name | Type | Description | Default | + |-------|---------------|-------------------------|---------| + | Value | System.Object | The value to build for. | | + + .OUTPUTS + System.String — The sort key. + + .EXAMPLE + PS> [IcingaSortKey]::FromValue('0,10') + + .NOTES + Numeric means a .NET numeric type; numeric strings use the natural string key. + #> + static [string] FromValue([object]$Value) + { + if ($null -eq $Value) { + return ''; + } + + if ($Value -is [int] -or $Value -is [long] -or $Value -is [uint32] -or $Value -is [uint64] -or $Value -is [int16] -or $Value -is [uint16] -or $Value -is [byte] -or $Value -is [sbyte] -or $Value -is [double] -or $Value -is [single] -or $Value -is [decimal]) { + # Shifting by 1E20 makes every supported number positive, so a fixed + # width keeps the ordinal order numeric for negative values as well. + return ([decimal]$Value + [decimal]100000000000000000000).ToString('000000000000000000000.0000000000', [System.Globalization.CultureInfo]::InvariantCulture); + } + + [string]$Text = ([string]$Value).ToUpperInvariant(); + [string]$Key = ''; + + foreach ($Part in [regex]::Matches($Text, '\d+|\D+')) { + [string]$Chunk = $Part.Value; + + if ([char]::IsDigit($Chunk[0])) { + [string]$Digits = $Chunk.TrimStart('0'); + $Key += $Digits.Length.ToString('000') + $Digits; + } else { + $Key += $Chunk; + } + } + + return $Key; + } + + <# + .SYNOPSIS + Read a property from a hashtable or an object + + .DESCRIPTION + Returns the value stored under the key for dictionaries and the member value + for every other object, or $null when the object itself is $null. + + .PARAMETER InputObject + | Name | Type | Description | Default | + |-------------|---------------|----------------------|---------| + | InputObject | System.Object | Object to read from. | | + + .PARAMETER Name + | Name | Type | Description | Default | + |------|---------------|---------------------|---------| + | Name | System.String | Key or member name. | | + + .OUTPUTS + System.Object — The property value or $null. + + .EXAMPLE + PS> [IcingaSortKey]::GetMemberValue($Volume, 'Name') + + .NOTES + Internal helper of FromObject. + #> + static [object] GetMemberValue([object]$InputObject, [string]$Name) + { + if ($null -eq $InputObject) { + return $null; + } + + if ($InputObject -is [System.Collections.IDictionary]) { + return $InputObject[$Name]; + } + + return $InputObject.$Name; + } +} diff --git a/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 b/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 index 67b3f5a..b7d5203 100644 --- a/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 +++ b/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 @@ -1081,6 +1081,117 @@ function Set-InternalExitCodes() 'Severity' = 'Debug'; 'Area' = 'Tools'; }; + 'WindowsInformationClassUnknown' = @{ + 'Code' = 4200; + 'Message' = 'The requested CIM class does not exist on this system'; + 'Severity' = 'Debug'; + 'Area' = 'Tools'; + 'Description' = 'Optional classes such as MPIO_DISK_INFO are probed on purpose, so this is only logged at Debug level; plugins surface the error in their output'; + }; + 'WindowsInformationNamespaceInvalid' = @{ + 'Code' = 4201; + 'Message' = 'The requested CIM namespace does not exist on this system'; + 'Severity' = 'Debug'; + 'Area' = 'Tools'; + 'Description' = 'Optional namespaces are probed on purpose, so this is only logged at Debug level; plugins surface the error in their output'; + }; + 'WindowsInformationAccessDenied' = @{ + 'Code' = 4202; + 'Message' = 'Access to the requested CIM class was denied'; + 'Severity' = 'Error'; + 'Area' = 'Tools'; + 'Description' = 'The user running the check needs the "Enable Account" and "Remote Enable" WMI permissions on the namespace, for example through the "Remote Management Users" group'; + }; + 'WindowsInformationInvalidQuery' = @{ + 'Code' = 4203; + 'Message' = 'The CIM query is invalid, check the filter and the requested properties'; + 'Severity' = 'Error'; + 'Area' = 'Tools'; + }; + 'WindowsInformationQueryFailed' = @{ + 'Code' = 4204; + 'Message' = 'The CIM query failed with an unhandled error'; + 'Severity' = 'Error'; + 'Area' = 'Tools'; + }; + 'WindowsInformationClassNameMissing' = @{ + 'Code' = 4205; + 'Message' = 'No CIM class name was provided for the query'; + 'Severity' = 'Error'; + 'Area' = 'Tools'; + }; + 'WindowsInformationQueried' = @{ + 'Code' = 4210; + 'Message' = 'The CIM query completed successfully'; + 'Severity' = 'Debug'; + 'Area' = 'Tools'; + }; + 'ArrayFilterInvalidPattern' = @{ + 'Code' = 4250; + 'Message' = 'A filter pattern is no valid wildcard expression, the value is treated as not matching'; + 'Severity' = 'Warning'; + 'Area' = 'Tools'; + }; + 'DiskInformationVolumeQueryFailed' = @{ + 'Code' = 4300; + 'Message' = 'The volume data for the disk information could not be read'; + 'Severity' = 'Error'; + 'Area' = 'Provider'; + }; + 'DiskInformationPartitionQueryFailed' = @{ + 'Code' = 4301; + 'Message' = 'The partition data for the disk information could not be read'; + 'Severity' = 'Error'; + 'Area' = 'Provider'; + }; + 'DiskInformationDiskQueryFailed' = @{ + 'Code' = 4302; + 'Message' = 'The physical disk data for the disk information could not be read'; + 'Severity' = 'Error'; + 'Area' = 'Provider'; + }; + 'DiskInformationCollected' = @{ + 'Code' = 4350; + 'Message' = 'The disk information was collected successfully'; + 'Severity' = 'Debug'; + 'Area' = 'Provider'; + }; + 'DirectoryPathMissing' = @{ + 'Code' = 4400; + 'Message' = 'No directory path was provided'; + 'Severity' = 'Error'; + 'Area' = 'Provider'; + }; + 'DirectoryPathNotFound' = @{ + 'Code' = 4401; + 'Message' = 'The directory does not exist on this system'; + 'Severity' = 'Error'; + 'Area' = 'Provider'; + }; + 'DirectoryAccessDenied' = @{ + 'Code' = 4402; + 'Message' = 'Access to the directory was denied'; + 'Severity' = 'Error'; + 'Area' = 'Provider'; + }; + 'DirectoryFilterInvalid' = @{ + 'Code' = 4403; + 'Message' = 'A directory filter value is invalid'; + 'Severity' = 'Error'; + 'Area' = 'Provider'; + }; + 'DirectoryReadFailed' = @{ + 'Code' = 4404; + 'Message' = 'The directory could not be read'; + 'Severity' = 'Error'; + 'Area' = 'Provider'; + }; + 'DirectoryInformationCollected' = @{ + 'Code' = 4450; + 'Message' = 'The directory information was collected successfully'; + 'Severity' = 'Debug'; + 'Area' = 'Provider'; + }; 'WebUIAssetPathEmpty' = @{ 'Code' = 13000; 'Message' = 'No Web UI asset path was provided for retrieving the Web UI asset'; diff --git a/src/Plugins/Public/Invoke-IcingaCheckCPU.ps1 b/src/Plugins/Public/Invoke-IcingaCheckCPU.ps1 new file mode 100644 index 0000000..6f94a71 --- /dev/null +++ b/src/Plugins/Public/Invoke-IcingaCheckCPU.ps1 @@ -0,0 +1,217 @@ +<# +.SYNOPSIS +Check the processor load per core, per NUMA node and in total against thresholds + +.DESCRIPTION +Reads the '\Processor Information(*)\% Processor Time' performance counter and +builds a single IcingaPlugin container named 'CPU Load'. Windows reports one +instance per logical processor as ',', where the first number is the +NUMA node and the second the index within that node. Every NUMA node becomes a +'NUMA Node #' container holding a check per core plus its 'Node Total', and +the average of all cores becomes the 'Overall Load' check. The cores are numbered +across all nodes ('Core #0' to 'Core #'), so the second node of a host with +eight cores per node starts at 'Core #8'. Every check is evaluated immediately +against the warning and critical thresholds, so the plugin reports +CRITICAL/WARNING as soon as any core, node or the total breaches its threshold +(the default 'all must be OK' aggregation). + +'Node Total' and 'Overall Load' are the averages of the core values read in the +same request. Windows' own ',_Total' and '_Total' instances are not used, +because they are sampled in a slightly different window and would not match the +cores shown next to them. + +The counter is declared through New-IcingaPerformanceCounter, so the +performance-counter daemon keeps it warm. Without a running daemon the first +read in a new process pays the counter warm-up. A failed read is reported as +UNKNOWN with the counter error, for the whole plugin or for the single core; the +averages then use the cores that could be read. + +Compile() renders the nested plugin output, collects the performance data and +returns the Icinga exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). On the +main thread the output is written to the console; inside a background daemon it +is stored in the thread-local runtime state for the REST API instead. + +This plugin is Windows-only because it relies on the Windows performance counters. + +.PARAMETER Warning +| Name | Type | Description | Default | +|---------|---------------|--------------------------------------------------------------------|---------| +| Warning | System.String | Warning threshold in percent, using the Icinga threshold grammar. | | + +.PARAMETER Critical +| Name | Type | Description | Default | +|----------|---------------|---------------------------------------------------------------------|---------| +| Critical | System.String | Critical threshold in percent, using the Icinga threshold grammar. | | + +.PARAMETER Verbosity +| Name | Type | Description | Default | +|-----------|--------------|-----------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | + +.PARAMETER NoPerfData +| Name | Type | Description | Default | +|------------|----------------------------------------------|---------------------------------------|---------| +| NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | + +.OUTPUTS +System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). + +.EXAMPLE +PS> Invoke-IcingaCheckCPU -Warning 80 -Critical 90 + +Warns at 80% and goes critical at 90% load for any core, NUMA node or the total. + +.EXAMPLE +PS> Invoke-IcingaCheckCPU -Warning 80 -Critical 90 -Verbosity 2 + +Shows every NUMA node and core in the output, not only the ones that breach a +threshold. + +.NOTES +Windows-only. Reads the '\Processor Information(*)\% Processor Time' performance +counter; the user needs read access to the performance counters ('Performance +Monitor Users'). Perfdata labels are '_::ifw_cpu::load' with the core +numbered across all nodes, '_total::ifw_cpu::load' and +'totalload::ifw_cpu::load'. The integer exit code is the return value; an Icinga +command wrapper is expected to exit with it. +#> +function Invoke-IcingaCheckCPU() +{ + param ( + [string]$Warning = '', + [string]$Critical = '', + [int]$Verbosity = 0, + [switch]$NoPerfData = $false + ); + + [string]$CounterPath = '\Processor Information(*)\% Processor Time'; + + # Literal declaration, so the counter discovery at module start finds and warms it. + New-IcingaPerformanceCounter -Counter @('\Processor Information(*)\% Processor Time'); + + $CheckPackage = New-IcingaPlugin 'CPU Load'; + $CheckPackage.Verbose = $Verbosity; + + $Counters = Get-IcingaPerformanceCounter -Counter $CounterPath -StructureByInstance; + + [array]$Nodes = @(); + [hashtable]$NodeCores = @{ }; + + if ($null -ne $Counters) { + # Natural order puts the nodes and the cores of every node in numeric order. + foreach ($Instance in (ConvertTo-IcingaSortedArray -InputObject @($Counters.Keys))) { + [string[]]$Parts = ([string]$Instance).Split(','); + + # Skips '_Total' and ',_Total'; the totals are averaged from the cores. + if ($Parts.Count -ne 2 -or $Parts[1] -eq '_Total') { + continue; + } + + if ($NodeCores.ContainsKey($Parts[0]) -eq $false) { + $NodeCores[$Parts[0]] = @(); + $Nodes += $Parts[0]; + } + + $NodeCores[$Parts[0]] += $Instance; + } + } + + if ($Nodes.Count -eq 0) { + return $CheckPackage.SetError('Failed to read the performance counter {0}: no processor instance available', $CounterPath).Compile(); + } + + # The node and overall averages need every core value, so all checks are collected + # first and created afterwards in output order. + [array]$Entries = @(); + [int]$CoreNumber = 0; + [double]$OverallSum = 0; + [int]$OverallCount = 0; + + foreach ($Node in $Nodes) { + $NodePackage = New-IcingaPlugin ([string]::Format('NUMA Node #{0}', $Node)); + $CheckPackage.AddCheck($NodePackage).Commit(); + + [double]$NodeSum = 0; + [int]$NodeCount = 0; + + foreach ($Instance in $NodeCores[$Node]) { + $Value = Get-IcingaPerformanceCounterValue -InputObject $Counters[$Instance]['Processor Information']['% Processor Time']; + $Entry = @{ + 'Parent' = $NodePackage; + 'Name' = [string]::Format('Core #{0}', $CoreNumber); + 'Index' = [string]::Format('{0}_{1}', $Node, $CoreNumber); + 'Value' = $null; + 'Error' = $null; + }; + + $CoreNumber += 1; + + if ($null -eq $Value -or $Value -is [string]) { + $Entry['Error'] = [string]$Value; + } else { + $Entry['Value'] = [double]$Value; + $NodeSum += [double]$Value; + $NodeCount += 1; + } + + $Entries += $Entry; + } + + $NodeTotal = @{ + 'Parent' = $NodePackage; + 'Name' = 'Node Total'; + 'Index' = [string]::Format('{0}_total', $Node); + 'Value' = $null; + 'Error' = 'no core of this NUMA node could be read'; + }; + + if ($NodeCount -ne 0) { + $NodeTotal['Value'] = $NodeSum / $NodeCount; + $NodeTotal['Error'] = $null; + } + + $Entries += $NodeTotal; + $OverallSum += $NodeSum; + $OverallCount += $NodeCount; + } + + $OverallLoad = @{ + 'Parent' = $CheckPackage; + 'Name' = 'Overall Load'; + 'Index' = 'totalload'; + 'Value' = $null; + 'Error' = 'no processor core could be read'; + }; + + if ($OverallCount -ne 0) { + $OverallLoad['Value'] = $OverallSum / $OverallCount; + $OverallLoad['Error'] = $null; + } + + $Entries += $OverallLoad; + + foreach ($Entry in $Entries) { + if ($null -eq $Entry['Value']) { + $Entry['Parent'].AddCheck( + (New-IcingaPlugin $Entry['Name']).SetError('Failed to read the performance counter: {0}', $Entry['Error']) + ).Commit(); + continue; + } + + $Check = New-IcingaPlugin $Entry['Name'] ([System.Math]::Round([double]$Entry['Value'], 2)) '%'; + $Check.NoPerfData = $NoPerfData; + + $Entry['Parent'].AddCheck( + $Check. + MetricIndex($Entry['Index']). + MetricLabel('load'). + Warning($Warning). + Critical($Critical). + Minimum('0'). + Maximum('100'). + CheckRange() + ).Commit(); + } + + return $CheckPackage.Compile(); +} diff --git a/src/Plugins/Public/Invoke-IcingaCheckDirectory.ps1 b/src/Plugins/Public/Invoke-IcingaCheckDirectory.ps1 new file mode 100644 index 0000000..7502c54 --- /dev/null +++ b/src/Plugins/Public/Invoke-IcingaCheckDirectory.ps1 @@ -0,0 +1,335 @@ +<# +.SYNOPSIS +Check the number and the sizes of the files in a directory against thresholds + +.DESCRIPTION +Reads the directory through Get-IcingaDirectoryInformation, which scans it once +and applies every name, time and size filter while reading, and builds a single +IcingaPlugin container named 'Directory Check: ""'. It holds the checks +'File Count', 'Folder Count', 'Total Size', 'Smallest File Size', 'Largest File +Size' and 'Average File Size' of the entries matching the filters, each evaluated +immediately against its own warning and critical thresholds, plus the +informational 'File Found' check. + +Warning and Critical apply to the file count (with CountFolderAsFile the matching +folders are counted as well); the size thresholds accept sizes ('2GiB', '500MB') +and the full Icinga range grammar. Without OverrideNotFound a missing directory +is reported as UNKNOWN and 'File Found' only informs whether anything matched. +With OverrideNotFound a missing directory counts as an empty one and 'File Found' +takes the given state when nothing matches, so a missing backup file can be +reported as CRITICAL. + +ShowFileList adds an informational 'File List' package with every matching entry +and its size; it raises the verbosity to at least 2 so the list is part of the +output. The list entries are not counted in the summary header. + +Performance data uses the label '::ifw_directory::' with the +metrics files, folders, totalsize, smallestfile, largestfile and averagefile, +sizes in bytes. A directory that cannot be read or an invalid filter value is +reported as UNKNOWN with its reason. + +.PARAMETER Path +| Name | Type | Description | Default | +|------|---------------|-----------------------------------------------|---------| +| Path | System.String | Directory to check, e.g. 'C:\ProgramData\Logs'. | | + +.PARAMETER FileNames +| Name | Type | Description | Default | +|-----------|--------------|------------------------------------------------------|---------| +| FileNames | System.Array | Wildcard patterns for the entry names, e.g. '*.log'. | @('*') | + +.PARAMETER Recurse +| Name | Type | Description | Default | +|---------|----------------------------------------------|----------------------------------|---------| +| Recurse | System.Management.Automation.SwitchParameter | Check every subdirectory as well. | False | + +.PARAMETER Warning +| Name | Type | Description | Default | +|---------|---------------|----------------------------------------------------------|---------| +| Warning | System.String | Warning threshold for the number of matching files. | | + +.PARAMETER Critical +| Name | Type | Description | Default | +|----------|---------------|----------------------------------------------------------|---------| +| Critical | System.String | Critical threshold for the number of matching files. | | + +.PARAMETER WarningTotalSize +| Name | Type | Description | Default | +|------------------|---------------|------------------------------------------------------|---------| +| WarningTotalSize | System.String | Warning threshold for the total size, e.g. '2GiB'. | | + +.PARAMETER CriticalTotalSize +| Name | Type | Description | Default | +|-------------------|---------------|------------------------------------------------------|---------| +| CriticalTotalSize | System.String | Critical threshold for the total size, e.g. '4GiB'. | | + +.PARAMETER WarningSmallestFile +| Name | Type | Description | Default | +|---------------------|---------------|-------------------------------------------------|---------| +| WarningSmallestFile | System.String | Warning threshold for the smallest file size. | | + +.PARAMETER CriticalSmallestFile +| Name | Type | Description | Default | +|----------------------|---------------|-------------------------------------------------|---------| +| CriticalSmallestFile | System.String | Critical threshold for the smallest file size. | | + +.PARAMETER WarningLargestFile +| Name | Type | Description | Default | +|--------------------|---------------|------------------------------------------------|---------| +| WarningLargestFile | System.String | Warning threshold for the largest file size. | | + +.PARAMETER CriticalLargestFile +| Name | Type | Description | Default | +|---------------------|---------------|------------------------------------------------|---------| +| CriticalLargestFile | System.String | Critical threshold for the largest file size. | | + +.PARAMETER WarningAverageFile +| Name | Type | Description | Default | +|--------------------|---------------|------------------------------------------------|---------| +| WarningAverageFile | System.String | Warning threshold for the average file size. | | + +.PARAMETER CriticalAverageFile +| Name | Type | Description | Default | +|---------------------|---------------|------------------------------------------------|---------| +| CriticalAverageFile | System.String | Critical threshold for the average file size. | | + +.PARAMETER CountFolderAsFile +| Name | Type | Description | Default | +|-------------------|----------------------------------------------|------------------------------------------------|---------| +| CountFolderAsFile | System.Management.Automation.SwitchParameter | Add the matching folders to the file count. | False | + +.PARAMETER ShowFileList +| Name | Type | Description | Default | +|--------------|----------------------------------------------|--------------------------------------------------------------|---------| +| ShowFileList | System.Management.Automation.SwitchParameter | List every matching entry; can make the output very large. | False | + +.PARAMETER ChangeTimeEqual +| Name | Type | Description | Default | +|-----------------|---------------|---------------------------------------------------------------|---------| +| ChangeTimeEqual | System.String | Only entries last written on the day this long ago, e.g. '1d'. | | + +.PARAMETER ChangeYoungerThan +| Name | Type | Description | Default | +|-------------------|---------------|-----------------------------------------------------------|---------| +| ChangeYoungerThan | System.String | Only entries last written within this duration, e.g. '5d'. | | + +.PARAMETER ChangeOlderThan +| Name | Type | Description | Default | +|-----------------|---------------|-------------------------------------------------------------|---------| +| ChangeOlderThan | System.String | Only entries last written longer ago than this, e.g. '10d'. | | + +.PARAMETER CreationTimeEqual +| Name | Type | Description | Default | +|-------------------|---------------|-----------------------------------------------------------|---------| +| CreationTimeEqual | System.String | Only entries created on the day this long ago, e.g. '1d'. | | + +.PARAMETER CreationOlderThan +| Name | Type | Description | Default | +|-------------------|---------------|--------------------------------------------------------|---------| +| CreationOlderThan | System.String | Only entries created longer ago than this, e.g. '10d'. | | + +.PARAMETER CreationYoungerThan +| Name | Type | Description | Default | +|---------------------|---------------|------------------------------------------------------|---------| +| CreationYoungerThan | System.String | Only entries created within this duration, e.g. '5d'. | | + +.PARAMETER AccessYoungerThan +| Name | Type | Description | Default | +|-------------------|---------------|------------------------------------------------------------|---------| +| AccessYoungerThan | System.String | Only entries last accessed within this duration, e.g. '5d'. | | + +.PARAMETER AccessOlderThan +| Name | Type | Description | Default | +|-----------------|---------------|--------------------------------------------------------------|---------| +| AccessOlderThan | System.String | Only entries last accessed longer ago than this, e.g. '10d'. | | + +.PARAMETER FileSizeGreaterThan +| Name | Type | Description | Default | +|---------------------|---------------|----------------------------------------------|---------| +| FileSizeGreaterThan | System.String | Only files larger than this size, e.g. '20MB'. | | + +.PARAMETER FileSizeSmallerThan +| Name | Type | Description | Default | +|---------------------|---------------|----------------------------------------------|---------| +| FileSizeSmallerThan | System.String | Only files smaller than this size, e.g. '5MB'. | | + +.PARAMETER OverrideNotFound +| Name | Type | Description | Default | +|------------------|---------------|-----------------------------------------------------------------------------|---------| +| OverrideNotFound | System.String | State when nothing matches: Ok, Warning, Critical, Unknown; a missing path counts as empty. | | + +.PARAMETER Verbosity +| Name | Type | Description | Default | +|-----------|--------------|-----------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | + +.PARAMETER NoPerfData +| Name | Type | Description | Default | +|------------|----------------------------------------------|---------------------------------------|---------| +| NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | + +.OUTPUTS +System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). + +.EXAMPLE +PS> Invoke-IcingaCheckDirectory -Path 'C:\Users\Icinga\Downloads' -Warning 20 -Critical 30 + +Warns when the directory holds more than 20 and goes critical with more than 30 files. + +.EXAMPLE +PS> Invoke-IcingaCheckDirectory -Path 'D:\Logs' -Recurse -FileNames '*.log' -ChangeOlderThan '30d' -Critical 0 + +Goes critical as soon as any log file below D:\Logs is older than 30 days. + +.EXAMPLE +PS> Invoke-IcingaCheckDirectory -Path 'C:\Backup' -FileNames '*.bak' -ChangeYoungerThan '1d' -OverrideNotFound 'Critical' + +Goes critical when no backup file was written within the last day. + +.NOTES +Windows-only. Reads the file system through Get-IcingaDirectoryInformation; the +user needs list permission on every checked directory. The integer exit code is +the return value; an Icinga command wrapper is expected to exit with it. +#> +function Invoke-IcingaCheckDirectory() +{ + param ( + [string]$Path = '', + [array]$FileNames = @( '*' ), + [switch]$Recurse = $false, + [string]$Warning = '', + [string]$Critical = '', + [string]$WarningTotalSize = '', + [string]$CriticalTotalSize = '', + [string]$WarningSmallestFile = '', + [string]$CriticalSmallestFile = '', + [string]$WarningLargestFile = '', + [string]$CriticalLargestFile = '', + [string]$WarningAverageFile = '', + [string]$CriticalAverageFile = '', + [switch]$CountFolderAsFile = $false, + [switch]$ShowFileList = $false, + [string]$ChangeTimeEqual = '', + [string]$ChangeYoungerThan = '', + [string]$ChangeOlderThan = '', + [string]$CreationTimeEqual = '', + [string]$CreationOlderThan = '', + [string]$CreationYoungerThan = '', + [string]$AccessYoungerThan = '', + [string]$AccessOlderThan = '', + [string]$FileSizeGreaterThan = '', + [string]$FileSizeSmallerThan = '', + [ValidateSet('Ok', 'Warning', 'Critical', 'Unknown')] + [string]$OverrideNotFound = '', + [int]$Verbosity = 0, + [switch]$NoPerfData = $false + ); + + # The file list is informational and would stay hidden at lower verbosity. + if ($ShowFileList -and $Verbosity -lt 2) { + $Verbosity = 2; + } + + $CheckPackage = New-IcingaPlugin ([string]::Format('Directory Check: "{0}"', $Path)); + $CheckPackage.Verbose = $Verbosity; + + [hashtable]$DirectoryArguments = @{ + 'Path' = $Path; + 'FileNames' = $FileNames; + 'Recurse' = $Recurse; + 'ChangeTimeEqual' = $ChangeTimeEqual; + 'ChangeYoungerThan' = $ChangeYoungerThan; + 'ChangeOlderThan' = $ChangeOlderThan; + 'CreationTimeEqual' = $CreationTimeEqual; + 'CreationYoungerThan' = $CreationYoungerThan; + 'CreationOlderThan' = $CreationOlderThan; + 'AccessYoungerThan' = $AccessYoungerThan; + 'AccessOlderThan' = $AccessOlderThan; + 'FileSizeGreaterThan' = $FileSizeGreaterThan; + 'FileSizeSmallerThan' = $FileSizeSmallerThan; + 'IncludeFileList' = $ShowFileList; + 'IgnoreMissingPath' = ([string]::IsNullOrEmpty($OverrideNotFound) -eq $false); + }; + + $Directory = Get-IcingaDirectoryInformation @DirectoryArguments; + + if (Test-IcingaError -InputObject $Directory) { + return $CheckPackage.SetError($Directory).Compile(); + } + + [int]$FileCount = $Directory.FileCount; + + if ($CountFolderAsFile) { + $FileCount += $Directory.FolderCount; + } + + # Name, value, unit, metric label, warning and critical threshold of every check. + [array]$Metrics = @( + @('File Count', $FileCount, '', 'files', $Warning, $Critical), + @('Folder Count', $Directory.FolderCount, '', 'folders', '', ''), + @('Total Size', $Directory.TotalSize, 'B', 'totalsize', $WarningTotalSize, $CriticalTotalSize), + @('Smallest File Size', $Directory.SmallestFile, 'B', 'smallestfile', $WarningSmallestFile, $CriticalSmallestFile), + @('Largest File Size', $Directory.LargestFile, 'B', 'largestfile', $WarningLargestFile, $CriticalLargestFile), + @('Average File Size', [System.Math]::Round([double]$Directory.AverageSize, 0), 'B', 'averagefile', $WarningAverageFile, $CriticalAverageFile) + ); + + foreach ($Metric in $Metrics) { + $Check = New-IcingaPlugin $Metric[0] $Metric[1] $Metric[2]; + $Check.NoPerfData = $NoPerfData; + + # Perfdata label: ::ifw_directory:: (template auto-derived from the command). + $CheckPackage.AddCheck( + $Check. + MetricIndex($Path). + MetricLabel($Metric[3]). + Warning($Metric[4]). + Critical($Metric[5]). + CheckRange() + ).Commit(); + } + + [string]$FileFound = 'No'; + + if ($FileCount -ne 0) { + $FileFound = 'Yes'; + } + + $FoundCheck = New-IcingaPlugin 'File Found' $FileFound; + $FoundCheck.NoPerfData = $true; + + if ([string]::IsNullOrEmpty($OverrideNotFound)) { + $FoundCheck.SetNotice($FileFound).Commit(); + } elseif ($FileCount -ne 0 -or $OverrideNotFound -eq 'Ok') { + $FoundCheck.SetOk($FileFound, $true).Commit(); + } elseif ($OverrideNotFound -eq 'Warning') { + $FoundCheck.SetWarning($FileFound, $true).Commit(); + } elseif ($OverrideNotFound -eq 'Critical') { + $FoundCheck.SetCritical($FileFound, $true).Commit(); + } else { + $FoundCheck.SetUnknown($FileFound, $true).Commit(); + } + + $CheckPackage.AddCheck($FoundCheck).Commit(); + + if ($ShowFileList) { + $FileListPackage = New-IcingaPlugin 'File List'; + $FileListPackage.IsNotice = $true; + $UnitType = 'IcingaUnit' -as [type]; + + foreach ($Entry in (ConvertTo-IcingaSortedArray -InputObject @($Directory.FileList) -Property 'FullName')) { + [string]$Details = 'Folder'; + + if ($Entry -is [System.IO.FileInfo]) { + $Details = $UnitType::new([string]$Entry.Length, 'B', '', $false).OutputString; + } + + $FileListPackage.AddCheck( + (New-IcingaPlugin $Entry.FullName).SetNotice($Details) + ).Commit(); + } + + $CheckPackage.AddCheck($FileListPackage).Commit(); + } + + return $CheckPackage.Compile(); +} diff --git a/src/Plugins/Public/Invoke-IcingaCheckMemory.ps1 b/src/Plugins/Public/Invoke-IcingaCheckMemory.ps1 new file mode 100644 index 0000000..862cc79 --- /dev/null +++ b/src/Plugins/Public/Invoke-IcingaCheckMemory.ps1 @@ -0,0 +1,242 @@ +<# +.SYNOPSIS +Check the used physical memory, the memory paging rate and the page files against thresholds + +.DESCRIPTION +Builds a single IcingaPlugin container named 'Memory Usage' with the checks +'Used Memory' (installed physical memory minus the available memory, in bytes), +'Memory pages/sec' (hard page faults per second) and a 'PageFile Usage' package +with one check per page file (current usage in bytes). Every check is evaluated +immediately against its own warning and critical thresholds. The memory and page +file thresholds accept percentages of the respective size ('80%'), absolute sizes +('4GiB', '500MB') and the full Icinga range grammar. + +The available memory and the paging rate are read in one request from the +'\Memory\Available Bytes' and '\Memory\Pages/sec' performance counters, which the +performance-counter daemon keeps warm. The installed memory comes from +Win32_ComputerSystem and the page files from Win32_PageFileUsage. A page file +with a configured maximum size (Win32_PageFileSetting, only read when Windows does +not manage the page files automatically) is measured against that maximum, +otherwise against its currently allocated size. IncludePageFile and +ExcludePageFile filter the page files by name (wildcards allowed); the package is +left out when no page file remains. + +Performance data uses the labels 'memory::ifw_memory::used', +'memory::ifw_memory::pagessec' and '::ifw_pagefile::used' (for example +'cpagefilesys::ifw_pagefile::used'). A failed query or counter read is reported +as UNKNOWN with its reason. + +.PARAMETER Warning +| Name | Type | Description | Default | +|---------|---------------|---------------------------------------------------------------------|---------| +| Warning | System.String | Warning threshold for the used memory, e.g. '80%' or '12GiB'. | | + +.PARAMETER Critical +| Name | Type | Description | Default | +|----------|---------------|---------------------------------------------------------------------|---------| +| Critical | System.String | Critical threshold for the used memory, e.g. '90%' or '14GiB'. | | + +.PARAMETER PageFileWarning +| Name | Type | Description | Default | +|-----------------|---------------|--------------------------------------------------------------|---------| +| PageFileWarning | System.String | Warning threshold for every page file, e.g. '80%' or '2GiB'. | | + +.PARAMETER PageFileCritical +| Name | Type | Description | Default | +|------------------|---------------|---------------------------------------------------------------|---------| +| PageFileCritical | System.String | Critical threshold for every page file, e.g. '90%' or '3GiB'. | | + +.PARAMETER MemoryPagesSecWarning +| Name | Type | Description | Default | +|-----------------------|---------------|-----------------------------------------------|---------| +| MemoryPagesSecWarning | System.String | Warning threshold for the memory pages/sec. | | + +.PARAMETER MemoryPagesSecCritical +| Name | Type | Description | Default | +|------------------------|---------------|-----------------------------------------------|---------| +| MemoryPagesSecCritical | System.String | Critical threshold for the memory pages/sec. | | + +.PARAMETER IncludePageFile +| Name | Type | Description | Default | +|-----------------|--------------|----------------------------------------------------------|---------| +| IncludePageFile | System.Array | Only check page files matching these names (wildcards). | @() | + +.PARAMETER ExcludePageFile +| Name | Type | Description | Default | +|-----------------|--------------|------------------------------------------------------|---------| +| ExcludePageFile | System.Array | Skip page files matching these names (wildcards). | @() | + +.PARAMETER Verbosity +| Name | Type | Description | Default | +|-----------|--------------|-----------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | + +.PARAMETER NoPerfData +| Name | Type | Description | Default | +|------------|----------------------------------------------|---------------------------------------|---------| +| NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | + +.OUTPUTS +System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). + +.EXAMPLE +PS> Invoke-IcingaCheckMemory -Warning '80%' -Critical '90%' + +Warns at 80% and goes critical at 90% used physical memory. + +.EXAMPLE +PS> Invoke-IcingaCheckMemory -Warning '12GiB' -Critical '14GiB' -PageFileWarning '75%' -Verbosity 2 + +Uses absolute memory thresholds, checks the page files against 75% and lists every check. + +.NOTES +Windows-only. Reads the '\Memory\Available Bytes' and '\Memory\Pages/sec' +performance counters ('Performance Monitor Users') and the Win32_ComputerSystem, +Win32_PageFileUsage and Win32_PageFileSetting CIM classes. The integer exit code +is the return value; an Icinga command wrapper is expected to exit with it. +#> +function Invoke-IcingaCheckMemory() +{ + param ( + [string]$Warning = '', + [string]$Critical = '', + [string]$PageFileWarning = '', + [string]$PageFileCritical = '', + [string]$MemoryPagesSecWarning = '', + [string]$MemoryPagesSecCritical = '', + [array]$IncludePageFile = @(), + [array]$ExcludePageFile = @(), + [int]$Verbosity = 0, + [switch]$NoPerfData = $false + ); + + # Literal declaration, so the counter discovery at module start finds and warms them. + New-IcingaPerformanceCounter -Counter @('\Memory\Available Bytes', '\Memory\Pages/sec'); + + $CheckPackage = New-IcingaPlugin 'Memory Usage'; + $CheckPackage.Verbose = $Verbosity; + + $ComputerSystem = Get-IcingaWindowsInformation -ClassName 'Win32_ComputerSystem' -Property 'TotalPhysicalMemory', 'AutomaticManagedPagefile'; + + if (Test-IcingaError -InputObject $ComputerSystem) { + return $CheckPackage.SetError($ComputerSystem).Compile(); + } + + $PageFiles = Get-IcingaWindowsInformation -ClassName 'Win32_PageFileUsage' -Property 'Name', 'AllocatedBaseSize', 'CurrentUsage'; + + if (Test-IcingaError -InputObject $PageFiles) { + return $CheckPackage.SetError($PageFiles).Compile(); + } + + $Counters = Get-IcingaPerformanceCounter -Counter @('\Memory\Available Bytes', '\Memory\Pages/sec') -StructureByInstance; + $MemoryCounters = $null; + + if ($null -ne $Counters) { + $MemoryCounters = $Counters['Memory']; + } + + if ($null -eq $MemoryCounters) { + return $CheckPackage.SetError('Failed to read the performance counters of the category Memory').Compile(); + } + + [uint64]$TotalMemory = $ComputerSystem[0].TotalPhysicalMemory; + $Available = Get-IcingaPerformanceCounterValue -InputObject $MemoryCounters['Available Bytes']; + + if ($null -eq $Available -or $Available -is [string]) { + $CheckPackage.AddCheck( + (New-IcingaPlugin 'Used Memory').SetError('Failed to read the performance counter \Memory\Available Bytes: {0}', $Available) + ).Commit(); + } else { + [uint64]$UsedMemory = [System.Math]::Max([double]0, [double]$TotalMemory - [double]$Available); + $MemoryCheck = New-IcingaPlugin 'Used Memory' $UsedMemory 'B'; + $MemoryCheck.NoPerfData = $NoPerfData; + + $CheckPackage.AddCheck( + $MemoryCheck. + MetricIndex('memory'). + MetricLabel('used'). + Warning($Warning). + Critical($Critical). + BaseValue($TotalMemory). + Minimum('0'). + Maximum([string]$TotalMemory). + CheckRange() + ).Commit(); + } + + $PagesSec = Get-IcingaPerformanceCounterValue -InputObject $MemoryCounters['Pages/sec']; + + if ($null -eq $PagesSec -or $PagesSec -is [string]) { + $CheckPackage.AddCheck( + (New-IcingaPlugin 'Memory pages/sec').SetError('Failed to read the performance counter \Memory\Pages/sec: {0}', $PagesSec) + ).Commit(); + } else { + $PagesCheck = New-IcingaPlugin 'Memory pages/sec' ([System.Math]::Round([double]$PagesSec, 2)); + $PagesCheck.NoPerfData = $NoPerfData; + + $CheckPackage.AddCheck( + $PagesCheck. + MetricIndex('memory'). + MetricLabel('pagessec'). + Warning($MemoryPagesSecWarning). + Critical($MemoryPagesSecCritical). + CheckRange() + ).Commit(); + } + + # Configured maximum page file sizes in MB. A failed query only leaves the + # page files on their allocated size, it is no reason to fail the check. + [hashtable]$MaximumSizes = @{ }; + + if ($ComputerSystem[0].AutomaticManagedPagefile -eq $false) { + $PageFileSettings = Get-IcingaWindowsInformation -ClassName 'Win32_PageFileSetting' -Property 'Name', 'MaximumSize'; + + if ((Test-IcingaError -InputObject $PageFileSettings) -eq $false) { + foreach ($Setting in $PageFileSettings) { + $MaximumSizes[[string]$Setting.Name] = [uint64]$Setting.MaximumSize; + } + } + } + + $PageFilePackage = New-IcingaPlugin 'PageFile Usage'; + + foreach ($PageFile in (ConvertTo-IcingaSortedArray -InputObject @($PageFiles) -Property 'Name')) { + [string]$PageFileName = $PageFile.Name; + + if ((Test-IcingaArrayFilter -InputObject $PageFileName -Include $IncludePageFile -Exclude $ExcludePageFile) -eq $false) { + continue; + } + + # A maximum of 0 means the size of this page file is managed by Windows. + [uint64]$SizeMB = $PageFile.AllocatedBaseSize; + + if ($MaximumSizes.ContainsKey($PageFileName) -and $MaximumSizes[$PageFileName] -gt 0) { + $SizeMB = $MaximumSizes[$PageFileName]; + } + + [uint64]$Size = $SizeMB * 1MB; + [uint64]$Usage = [uint64]$PageFile.CurrentUsage * 1MB; + $PageFileCheck = New-IcingaPlugin $PageFileName $Usage 'B'; + $PageFileCheck.NoPerfData = $NoPerfData; + + # Perfdata label: ::ifw_pagefile::used (own template instead of ifw_memory). + $PageFilePackage.AddCheck( + $PageFileCheck. + MetricIndex($PageFileName). + MetricName('pagefile'). + MetricLabel('used'). + Warning($PageFileWarning). + Critical($PageFileCritical). + BaseValue($Size). + Minimum('0'). + Maximum([string]$Size). + CheckRange() + ).Commit(); + } + + if ($PageFilePackage.HasChecks()) { + $CheckPackage.AddCheck($PageFilePackage).Commit(); + } + + return $CheckPackage.Compile(); +} diff --git a/src/Plugins/Public/Invoke-IcingaCheckPartitionSpace.ps1 b/src/Plugins/Public/Invoke-IcingaCheckPartitionSpace.ps1 new file mode 100644 index 0000000..ee3137a --- /dev/null +++ b/src/Plugins/Public/Invoke-IcingaCheckPartitionSpace.ps1 @@ -0,0 +1,214 @@ +<# +.SYNOPSIS +Check the used or free space of the local partitions against thresholds + +.DESCRIPTION +Reads every local disk volume through Get-IcingaDiskInformation (Volume +entrypoint) and builds a single IcingaPlugin container named 'Used Partition +Space' (or 'Free Partition +Space' with CheckFreeSpace). Every volume becomes a child check whose value is +the used (or free) space in bytes, evaluated immediately against the warning and +critical thresholds with the volume size as base value. Thresholds therefore +accept percentages ('80%'), absolute sizes ('400GB', '1.5TiB') and the full Icinga +range grammar ('10%:' raises an alert below 10 percent). + +Volumes with a drive letter are named after the letter ('C'), volumes without +one after their label, or their volume path when they have no label. Include, +Exclude and RequiredPartition match that name (wildcards allowed; 'C', 'C:' and +'C:\' all select drive C). Every RequiredPartition that does not exist on the +host is reported CRITICAL. + +Performance data uses the label '::ifw_partitionspace::used' (or +'::free') in bytes, with the resolved thresholds in bytes and the volume size as +maximum. + +A failed volume query is reported as UNKNOWN with its reason. This plugin is +Windows-only because it relies on the Win32_Volume CIM class. + +.PARAMETER Warning +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------------------------------------------|---------| +| Warning | System.String | Warning threshold as percentage, size or Icinga range, e.g. '80%' or '400GB'. | | + +.PARAMETER Critical +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------------------------------------------------|---------| +| Critical | System.String | Critical threshold as percentage, size or Icinga range, e.g. '90%' or '450GB'. | | + +.PARAMETER Include +| Name | Type | Description | Default | +|---------|--------------|---------------------------------------------------------------------|---------| +| Include | System.Array | Only check partitions matching these letters or labels (wildcards). | @() | + +.PARAMETER Exclude +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------------------------|---------| +| Exclude | System.Array | Skip partitions matching these letters or labels (wildcards). | @() | + +.PARAMETER RequiredPartition +| Name | Type | Description | Default | +|-------------------|--------------|-----------------------------------------------------------------|---------| +| RequiredPartition | System.Array | Partitions that must exist; a missing one is reported CRITICAL. | @() | + +.PARAMETER CheckFreeSpace +| Name | Type | Description | Default | +|----------------|----------------------------------------------|---------------------------------------------------|---------| +| CheckFreeSpace | System.Management.Automation.SwitchParameter | Evaluate the free instead of the used space. | False | + +.PARAMETER IgnoreEmptyChecks +| Name | Type | Description | Default | +|-------------------|----------------------------------------------|----------------------------------------------------------------|---------| +| IgnoreEmptyChecks | System.Management.Automation.SwitchParameter | Return OK instead of UNKNOWN when no partition matches at all. | False | + +.PARAMETER SkipUnknown +| Name | Type | Description | Default | +|-------------|----------------------------------------------|--------------------------------------------------------------|---------| +| SkipUnknown | System.Management.Automation.SwitchParameter | Report OK instead of UNKNOWN for a volume without size data. | False | + +.PARAMETER Verbosity +| Name | Type | Description | Default | +|-----------|--------------|-----------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | + +.PARAMETER NoPerfData +| Name | Type | Description | Default | +|------------|----------------------------------------------|---------------------------------------|---------| +| NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | + +.OUTPUTS +System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). + +.EXAMPLE +PS> Invoke-IcingaCheckPartitionSpace -Warning '80%' -Critical '90%' + +Warns at 80% and goes critical at 90% used space on any local partition. + +.EXAMPLE +PS> Invoke-IcingaCheckPartitionSpace -CheckFreeSpace -Warning '50GB:' -Critical '10%:' -Include 'C', 'D' + +Warns when less than 50GB and goes critical when less than 10% are free on C: or D:. + +.EXAMPLE +PS> Invoke-IcingaCheckPartitionSpace -Warning '80%' -Critical '90%' -RequiredPartition 'E:' -Verbosity 2 + +Also reports CRITICAL when E: is missing and lists every partition in the output. + +.NOTES +Windows-only. Reads Win32_Volume and MSFT_Partition through +Get-IcingaDiskInformation. The integer exit code is the +return value; an Icinga command wrapper is expected to exit with it. +#> +function Invoke-IcingaCheckPartitionSpace() +{ + param ( + [string]$Warning = '', + [string]$Critical = '', + [array]$Include = @(), + [array]$Exclude = @(), + [array]$RequiredPartition = @(), + [switch]$CheckFreeSpace = $false, + [switch]$IgnoreEmptyChecks = $false, + [switch]$SkipUnknown = $false, + [int]$Verbosity = 0, + [switch]$NoPerfData = $false + ); + + [string]$PackageName = 'Used Partition Space'; + [string]$MetricLabel = 'used'; + + if ($CheckFreeSpace) { + $PackageName = 'Free Partition Space'; + $MetricLabel = 'free'; + } + + $CheckPackage = New-IcingaPlugin $PackageName; + $CheckPackage.Verbose = $Verbosity; + + $Volumes = Get-IcingaDiskInformation -Entrypoint 'Volume'; + + if (Test-IcingaError -InputObject $Volumes) { + return $CheckPackage.SetError($Volumes).Compile(); + } + + # Drive letters are matched without ':', '\' and '/', so 'C', 'C:' and 'C:\' all + # select drive C; the unchanged pattern keeps labels and volume paths matchable. + [array]$IncludeFilter = @(); + [array]$ExcludeFilter = @(); + + foreach ($Pattern in $Include) { + $IncludeFilter += [string]$Pattern; + $IncludeFilter += ([string]$Pattern -replace '[:\\/]', ''); + } + + foreach ($Pattern in $Exclude) { + $ExcludeFilter += [string]$Pattern; + $ExcludeFilter += ([string]$Pattern -replace '[:\\/]', ''); + } + + [array]$KnownPartitions = @(); + + foreach ($Volume in (ConvertTo-IcingaSortedArray -InputObject @($Volumes.Values) -Property 'Name')) { + [string]$PartitionName = $Volume.Name; + + if ([string]::IsNullOrEmpty($Volume.DriveLetter) -eq $false) { + $PartitionName = ([string]$Volume.DriveLetter).Replace(':', ''); + } elseif ([string]::IsNullOrEmpty($Volume.Label) -eq $false) { + $PartitionName = $Volume.Label; + } + + $KnownPartitions += $PartitionName; + + if ((Test-IcingaArrayFilter -InputObject $PartitionName -Include $IncludeFilter -Exclude $ExcludeFilter) -eq $false) { + continue; + } + + [string]$CheckName = [string]::Format('Partition {0}', $PartitionName); + + if ($null -eq $Volume.Size -or $null -eq $Volume.FreeSpace -or $null -eq $Volume.UsedSpace -or $Volume.Size -eq 0) { + $PartitionCheck = New-IcingaPlugin $CheckName; + + if ($SkipUnknown) { + $PartitionCheck.SetOk('No partition size available', $true).Commit(); + } else { + $PartitionCheck.SetError('No partition size available').Commit(); + } + + $CheckPackage.AddCheck($PartitionCheck).Commit(); + continue; + } + + [uint64]$Value = $Volume.UsedSpace; + + if ($CheckFreeSpace) { + $Value = $Volume.FreeSpace; + } + + $PartitionCheck = New-IcingaPlugin $CheckName $Value 'B'; + $PartitionCheck.NoPerfData = $NoPerfData; + + # Perfdata label: ::ifw_partitionspace::used|free (template auto-derived from the command). + $CheckPackage.AddCheck( + $PartitionCheck. + MetricIndex($PartitionName). + MetricLabel($MetricLabel). + Warning($Warning). + Critical($Critical). + BaseValue($Volume.Size). + Minimum('0'). + Maximum([string]$Volume.Size). + CheckRange() + ).Commit(); + } + + $CheckPackage.AddMissingChecks($RequiredPartition, $KnownPartitions, 'Partition {0}', 'Mandatory partition not found on host', 2, '[:\\/]+$').Commit(); + + if ($CheckPackage.HasChecks() -eq $false) { + if ($IgnoreEmptyChecks) { + return $CheckPackage.SetOk('No partition matches the given filter', $true).Compile(); + } + + return $CheckPackage.SetError('No partition matches the given filter').Compile(); + } + + return $CheckPackage.Compile(); +} diff --git a/src/Plugins/Public/Invoke-IcingaCheckPerfCounter.ps1 b/src/Plugins/Public/Invoke-IcingaCheckPerfCounter.ps1 new file mode 100644 index 0000000..366545c --- /dev/null +++ b/src/Plugins/Public/Invoke-IcingaCheckPerfCounter.ps1 @@ -0,0 +1,256 @@ +<# +.SYNOPSIS +Check any Windows performance counter against thresholds + +.DESCRIPTION +Reads every given performance counter in one request and builds a single +IcingaPlugin container named 'Performance Counter'. Every requested counter +becomes a package named after its path, holding one check per instance: a +wildcard path such as '\Processor(*)\% Processor Time' is expanded to every live +instance, a concrete path such as '\Memory\Available Bytes' yields one check. All +checks are evaluated immediately against the same warning and critical +thresholds, using the full Icinga range grammar. + +Every value gets its unit from the counter type and name, so it is rendered and +compared through the unit conversion. Percent counters (name starting with '%' +or a percent counter type) use '%'. Timer counters such as 'Avg. Disk sec/Read', +'System Up Time' or 'Elapsed Time' are durations in seconds and render as '4ms' +or '1d 2h 3m 4s'; their thresholds accept durations ('30m', '1d:'). Counters with +'Bytes' in the name are sizes in bytes, 'KBytes' and 'MBytes' counters are scaled +to bytes as well; they render as '8.93GiB' and their thresholds accept sizes +('500MB'). Rates such as 'Pages/sec' and plain counts keep a plain number. + +IncludeCounter and ExcludeCounter filter the instance paths (wildcards allowed, +for example '*_Total*'). An instance that cannot be read is skipped; when no +instance of a counter can be read, or a concrete counter fails, the counter is +reported as UNKNOWN with the first counter error. With IgnoreEmptyChecks the +plugin reports OK instead of UNKNOWN when the filters leave no counter at all. + +Counters that are requested repeatedly are kept warm by the performance-counter +daemon. Without a running daemon the first read of a counter in a new process +pays the counter warm-up. + +Performance data uses the label '::ifw_perfcounter::' +with '%' spelled out as 'percent', for example +'processor::ifw_perfcounter::percentprocessortime2' for core 2 or +'memory::ifw_perfcounter::availablebytes' for a counter without an instance. + +.PARAMETER PerfCounter +| Name | Type | Description | Default | +|-------------|--------------|------------------------------------------------------------------------|---------| +| PerfCounter | System.Array | Counter paths to check, e.g. '\Processor(*)\% Processor Time'. | @() | + +.PARAMETER Warning +| Name | Type | Description | Default | +|---------|---------------|----------------------------------------------------------|---------| +| Warning | System.String | Warning threshold in the counter's unit, e.g. '80', '500MB' or '30m'. | | + +.PARAMETER Critical +| Name | Type | Description | Default | +|----------|---------------|----------------------------------------------------------|---------| +| Critical | System.String | Critical threshold in the counter's unit, e.g. '90', '1GB' or '1h'. | | + +.PARAMETER IncludeCounter +| Name | Type | Description | Default | +|----------------|--------------|--------------------------------------------------------------|---------| +| IncludeCounter | System.Array | Only check instance paths matching these patterns. | @() | + +.PARAMETER ExcludeCounter +| Name | Type | Description | Default | +|----------------|--------------|--------------------------------------------------------------|---------| +| ExcludeCounter | System.Array | Skip instance paths matching these patterns. | @() | + +.PARAMETER IgnoreEmptyChecks +| Name | Type | Description | Default | +|-------------------|----------------------------------------------|--------------------------------------------------------------|---------| +| IgnoreEmptyChecks | System.Management.Automation.SwitchParameter | Return OK instead of UNKNOWN when no counter remains to check. | False | + +.PARAMETER Verbosity +| Name | Type | Description | Default | +|-----------|--------------|-----------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | + +.PARAMETER NoPerfData +| Name | Type | Description | Default | +|------------|----------------------------------------------|---------------------------------------|---------| +| NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | + +.OUTPUTS +System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). + +.EXAMPLE +PS> Invoke-IcingaCheckPerfCounter -PerfCounter '\Processor(*)\% Processor Time' -Warning 80 -Critical 90 -ExcludeCounter '*_Total*' + +Checks the load of every processor instance except the total. + +.EXAMPLE +PS> Invoke-IcingaCheckPerfCounter -PerfCounter '\Memory\Pages/sec', '\System\Processor Queue Length' -Critical 10 -Verbosity 2 + +Checks two concrete counters against the same critical threshold. + +.NOTES +Windows-only. Reads the Windows performance counters; the user needs read access +to them ('Performance Monitor Users'). The integer exit code is the return value; +an Icinga command wrapper is expected to exit with it. +#> +function Invoke-IcingaCheckPerfCounter() +{ + param ( + [array]$PerfCounter = @(), + [string]$Warning = '', + [string]$Critical = '', + [array]$IncludeCounter = @(), + [array]$ExcludeCounter = @(), + [switch]$IgnoreEmptyChecks = $false, + [int]$Verbosity = 0, + [switch]$NoPerfData = $false + ); + + $CheckPackage = New-IcingaPlugin 'Performance Counter'; + $CheckPackage.Verbose = $Verbosity; + + [array]$Requested = @(); + + foreach ($CounterPath in $PerfCounter) { + if ([string]::IsNullOrEmpty([string]$CounterPath) -eq $false) { + $Requested += [string]$CounterPath; + } + } + + if ($Requested.Count -eq 0) { + return $CheckPackage.SetError('No performance counter was provided').Compile(); + } + + # Counter types whose value is a percentage or a duration in seconds. Some + # percent counters report an unnamed type, so the '%' name prefix counts as well. + [array]$PercentTypes = @( + 'Timer100Ns', 'Timer100NsInverse', 'CounterTimer', 'CounterTimerInverse', + 'CounterMultiTimer', 'CounterMultiTimerInverse', 'CounterMultiTimer100Ns', + 'CounterMultiTimer100NsInverse', 'RawFraction', 'SampleFraction' + ); + [array]$TimeTypes = @( 'AverageTimer32', 'ElapsedTime' ); + + $Counters = Get-IcingaPerformanceCounter -Counter $Requested; + + if ($null -eq $Counters) { + return $CheckPackage.SetError('Failed to read the performance counters {0}', ($Requested -join ', ')).Compile(); + } + + $CounterType = 'IcingaPerformanceCounter' -as [type]; + + foreach ($CounterPath in $Requested) { + $CounterPackage = New-IcingaPlugin $CounterPath; + $Parsed = $CounterType::ParsePath($CounterPath); + + if ($Parsed.Valid -eq $false) { + $CheckPackage.AddCheck( + $CounterPackage.SetError('Invalid performance counter path, expected \Category\Counter or \Category(Instance)\Counter') + ).Commit(); + continue; + } + + # A wildcard result is keyed by every expanded instance path, a concrete + # request is the counter result itself. + [hashtable]$Instances = @{ }; + + if ($Parsed.Instance -eq '*') { + if ($Counters[$CounterPath] -is [hashtable]) { + $Instances = $Counters[$CounterPath]; + } + } else { + $Instances[$CounterPath] = $Counters[$CounterPath]; + } + + [bool]$Filtered = $false; + [string]$FirstError = ''; + + foreach ($InstancePath in (ConvertTo-IcingaSortedArray -InputObject @($Instances.Keys))) { + if ((Test-IcingaArrayFilter -InputObject $InstancePath -Include $IncludeCounter -Exclude $ExcludeCounter) -eq $false) { + $Filtered = $true; + continue; + } + + $Value = Get-IcingaPerformanceCounterValue -InputObject $Instances[$InstancePath]; + + if ($null -eq $Value -or $Value -is [string]) { + if ([string]::IsNullOrEmpty($FirstError)) { + $FirstError = [string]$Value; + } + continue; + } + + # The label names the counter and the instance ('percentprocessortime2'), so + # several counters of one category never share a label. '%' is spelled out + # because the label sanitizing would drop it. + $Instance = $CounterType::ParsePath($InstancePath); + [string]$Label = $Instance.Counter.Replace('%', 'percent') + $Instance.Instance; + + [string]$Type = [string]$Instances[$InstancePath]['type']; + [string]$Unit = ''; + [double]$Scale = 1; + + if ($Instance.Counter.StartsWith('%') -or $PercentTypes -contains $Type) { + $Unit = '%'; + } elseif ($TimeTypes -contains $Type -or $Instance.Counter -match '(?i)\bsec/') { + $Unit = 's'; + } elseif ($Instance.Counter -match '(?i)(KBytes|Kilobytes)') { + $Unit = 'B'; + $Scale = 1KB; + } elseif ($Instance.Counter -match '(?i)(MBytes|Megabytes)') { + $Unit = 'B'; + $Scale = 1MB; + } elseif ($Instance.Counter -match '(?i)Bytes') { + $Unit = 'B'; + } + + [double]$Measured = [double]$Value * $Scale; + + # Bytes are indivisible (a byte rate is rounded to whole bytes as well), an + # elapsed time such as the uptime needs no sub-second part and percentages + # keep two decimals like the other plugins. Timer averages keep their precision. + if ($Unit -eq 'B' -or $Type -eq 'ElapsedTime') { + $Measured = [System.Math]::Round($Measured, 0); + } elseif ($Unit -eq '%') { + $Measured = [System.Math]::Round($Measured, 2); + } + + $Check = New-IcingaPlugin $InstancePath $Measured $Unit; + $Check.NoPerfData = $NoPerfData; + + # Perfdata label: ::ifw_perfcounter:: (template auto-derived from the command). + $CounterPackage.AddCheck( + $Check. + MetricIndex($Instance.Category). + MetricLabel($Label). + Warning($Warning). + Critical($Critical). + CheckRange() + ).Commit(); + } + + if ($CounterPackage.HasChecks() -eq $false) { + # Instances that were filtered out on purpose are no failure. + if ($Filtered -and [string]::IsNullOrEmpty($FirstError)) { + continue; + } + + if ([string]::IsNullOrEmpty($FirstError)) { + $FirstError = 'no instance of this counter exists'; + } + + $CounterPackage.SetError('Failed to read the performance counter: {0}', $FirstError).Commit(); + } + + $CheckPackage.AddCheck($CounterPackage).Commit(); + } + + if ($CheckPackage.HasChecks() -eq $false) { + if ($IgnoreEmptyChecks) { + return $CheckPackage.SetOk('No performance counter matches the given filter', $true).Compile(); + } + + return $CheckPackage.SetError('No performance counter matches the given filter').Compile(); + } + + return $CheckPackage.Compile(); +} diff --git a/src/Plugins/Public/Invoke-IcingaCheckService.ps1 b/src/Plugins/Public/Invoke-IcingaCheckService.ps1 new file mode 100644 index 0000000..01c2252 --- /dev/null +++ b/src/Plugins/Public/Invoke-IcingaCheckService.ps1 @@ -0,0 +1,267 @@ +<# +.SYNOPSIS +Check the state of Windows services against an expected status + +.DESCRIPTION +Queries every service from the Win32_Service CIM class once and builds a single +IcingaPlugin container named 'Services'. Each selected service becomes a child +check comparing its current state with the expected status; a mismatch raises the +state chosen with OverrideNotOk (CRITICAL by default). + +When no service is given, every service with the 'Automatic' start mode is +checked: it is expected to be running, except when it is stopped with exit code +0, which means it ended on purpose and is reported OK. When services are given +by name or display name (wildcards allowed), they are compared against Status, +optionally narrowed down by their startup type. Every given name without a +wildcard that matches no service on the system is reported with the state chosen +with OverrideNotFound (UNKNOWN by default). + +Service states and startup types are resolved through the IcingaServiceStatus +and IcingaServiceStartupType data types. Performance data contains the numeric +state of each explicitly selected service ('::ifw_service::state', 0 +Unknown, 1 Stopped to 7 Paused) and per-state counters of all checked services +('summary::ifw_service::' and '::count'). + +This plugin is Windows-only because it relies on the Win32_Service CIM class. + +.PARAMETER Service +| Name | Type | Description | Default | +|---------|----------------|--------------------------------------------------------------------------|---------| +| Service | System.Array | Service names or display names to check, wildcards allowed. Empty checks all automatic services. | @() | + +.PARAMETER Exclude +| Name | Type | Description | Default | +|---------|--------------|---------------------------------------------------------------|---------| +| Exclude | System.Array | Service names or display names to skip, wildcards allowed. | @() | + +.PARAMETER Status +| Name | Type | Description | Default | +|--------|---------------------|---------------------------------------------------------------------------------------------------|---------| +| Status | IcingaServiceStatus | Expected status of the given services: Stopped, StartPending, StopPending, Running, ContinuePending, PausePending, Paused or Unknown. | Running | + +.PARAMETER FilterStartupType +| Name | Type | Description | Default | +|-------------------|----------------------------|-----------------------------------------------------------------------------------------------------|---------| +| FilterStartupType | IcingaServiceStartupType[] | Only check given services with one of these startup types: Boot, System, Automatic, Manual, Disabled, Unknown. | @() | + +.PARAMETER MitigateUnknown +| Name | Type | Description | Default | +|-----------------|----------------------------------------------|--------------------------------------------------------------|---------| +| MitigateUnknown | System.Management.Automation.SwitchParameter | Return OK instead of UNKNOWN when no service matches at all. | False | + +.PARAMETER OverrideNotOk +| Name | Type | Description | Default | +|---------------|---------------|-------------------------------------------------------------------------------|----------| +| OverrideNotOk | System.String | State for a service not in the expected status: Ok, Warning, Critical, Unknown. | Critical | + +.PARAMETER OverrideNotFound +| Name | Type | Description | Default | +|------------------|---------------|--------------------------------------------------------------------|---------| +| OverrideNotFound | System.String | State for a given service that does not exist: Ok, Warning, Critical, Unknown. | Unknown | + +.PARAMETER Verbosity +| Name | Type | Description | Default | +|-----------|--------------|-----------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | + +.PARAMETER NoPerfData +| Name | Type | Description | Default | +|------------|----------------------------------------------|---------------------------------------|---------| +| NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | + +.OUTPUTS +System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). + +.EXAMPLE +PS> Invoke-IcingaCheckService + +Checks that every automatic service is running or ended with exit code 0. + +.EXAMPLE +PS> Invoke-IcingaCheckService -Service 'Spooler', 'W32Time' -OverrideNotOk 'Warning' + +Warns when the print spooler or the time service is not running. + +.EXAMPLE +PS> Invoke-IcingaCheckService -Service 'Windows Update*' -Exclude 'wuauserv' -Status 'Stopped' -Verbosity 2 + +Expects every service whose display name starts with 'Windows Update', except +wuauserv, to be stopped and lists all of them in the output. + +.NOTES +Windows-only. Reads the Win32_Service CIM class through +Get-IcingaWindowsInformation; a failed query is reported as UNKNOWN with its +reason. The integer exit code is the return value; an Icinga command wrapper is +expected to exit with it. +#> +function Invoke-IcingaCheckService() +{ + param ( + [array]$Service = @(), + [array]$Exclude = @(), + [IcingaServiceStatus]$Status = 'Running', + [IcingaServiceStartupType[]]$FilterStartupType = @(), + [switch]$MitigateUnknown = $false, + [ValidateSet('Ok', 'Warning', 'Critical', 'Unknown')] + [string]$OverrideNotOk = 'Critical', + [ValidateSet('Ok', 'Warning', 'Critical', 'Unknown')] + [string]$OverrideNotFound = 'Unknown', + [int]$Verbosity = 0, + [switch]$NoPerfData = $false + ); + + [hashtable]$SummaryLabels = @{ + ([IcingaServiceStatus]::Stopped) = 'stopped'; + ([IcingaServiceStatus]::StartPending) = 'pendingstarted'; + ([IcingaServiceStatus]::StopPending) = 'pendingstopped'; + ([IcingaServiceStatus]::Running) = 'running'; + ([IcingaServiceStatus]::ContinuePending) = 'pendingcontinued'; + ([IcingaServiceStatus]::PausePending) = 'pendingpaused'; + ([IcingaServiceStatus]::Paused) = 'paused'; + }; + + $CheckPackage = New-IcingaPlugin 'Services'; + $CheckPackage.Verbose = $Verbosity; + + $AllServices = Get-IcingaWindowsInformation -ClassName 'Win32_Service' -Property 'Name', 'DisplayName', 'State', 'StartMode', 'ExitCode'; + + if (Test-IcingaError -InputObject $AllServices) { + return $CheckPackage.SetError($AllServices).Compile(); + } + + [hashtable]$KnownServices = @{ }; + + foreach ($ServiceEntry in $AllServices) { + $KnownServices[[string]$ServiceEntry.Name] = $true; + $KnownServices[[string]$ServiceEntry.DisplayName] = $true; + } + + $SummaryCount = [ordered]@{ + 'stopped' = 0; + 'pendingstarted' = 0; + 'pendingstopped' = 0; + 'running' = 0; + 'pendingcontinued' = 0; + 'pendingpaused' = 0; + 'paused' = 0; + }; + + $MetricPackage = New-IcingaPlugin 'Service Metrics'; + $MetricPackage.IsHidden = $true; + [bool]$AutoMode = ($Service.Count -eq 0); + [int]$ServiceCount = 0; + $StatusMap = 'IcingaServiceStatusMap' -as [type]; + $StartupTypeMap = 'IcingaServiceStartupTypeMap' -as [type]; + + foreach ($ServiceEntry in (ConvertTo-IcingaSortedArray -InputObject $AllServices -Property 'Name')) { + [string]$ServiceName = $ServiceEntry.Name; + [string]$DisplayName = $ServiceEntry.DisplayName; + [IcingaServiceStatus]$State = $StatusMap::Resolve($ServiceEntry.State); + [IcingaServiceStartupType]$StartupType = $StartupTypeMap::Resolve($ServiceEntry.StartMode); + [IcingaServiceStatus]$Expected = $Status; + + if ((Test-IcingaArrayFilter -InputObject $ServiceName -Exclude $Exclude) -eq $false -or (Test-IcingaArrayFilter -InputObject $DisplayName -Exclude $Exclude) -eq $false) { + continue; + } + + if ($AutoMode) { + if ($StartupType -ne [IcingaServiceStartupType]::Automatic) { + continue; + } + + $Expected = [IcingaServiceStatus]::Running; + + # A stopped automatic service with exit code 0 ended on purpose (for + # example a trigger-start service) and is not a failure. + if ($State -ne [IcingaServiceStatus]::Running -and $ServiceEntry.ExitCode -eq 0) { + $Expected = $State; + } + } else { + if ((Test-IcingaArrayFilter -InputObject $ServiceName -Include $Service) -eq $false -and (Test-IcingaArrayFilter -InputObject $DisplayName -Include $Service) -eq $false) { + continue; + } + + if ($FilterStartupType.Count -ne 0 -and $FilterStartupType -notcontains $StartupType) { + continue; + } + } + + $ServiceCheck = New-IcingaPlugin ([string]::Format('Service "{0} ({1})"', $DisplayName, $ServiceName)) ([string]$State); + + if ($OverrideNotOk -eq 'Warning') { + $ServiceCheck.Warning([string]$Expected).CheckNotEqual().Commit(); + } else { + $ServiceCheck.Critical([string]$Expected).CheckNotEqual().Commit(); + } + + # An empty message keeps the comparison text; the lock stops the critical + # comparison result from escalating the overridden state again. + if ($State -ne $Expected) { + if ($OverrideNotOk -eq 'Ok') { + $ServiceCheck.SetOk('', $true).Commit(); + } elseif ($OverrideNotOk -eq 'Unknown') { + $ServiceCheck.SetUnknown('', $true).Commit(); + } + } + + $CheckPackage.AddCheck($ServiceCheck).Commit(); + $ServiceCount++; + + if ($SummaryLabels.ContainsKey($State)) { + $SummaryCount[$SummaryLabels[$State]] += 1; + } + + if ($AutoMode -or $NoPerfData) { + continue; + } + + $MetricPackage.AddCheck( + (New-IcingaPlugin $ServiceName ([int]$State)).MetricIndex($ServiceName).MetricLabel('state').CheckRange() + ).Commit(); + } + + [hashtable]$NotFoundStates = @{ + 'Ok' = 0; + 'Warning' = 1; + 'Critical' = 2; + 'Unknown' = 3; + }; + + # Wildcard arguments select services instead of naming one, so only plain + # names can be missing. + [array]$RequiredServices = @(); + + foreach ($Filter in $Service) { + if ([System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters([string]$Filter) -eq $false) { + $RequiredServices += [string]$Filter; + } + } + + $CheckPackage.AddMissingChecks($RequiredServices, @($KnownServices.Keys), '{0}', 'Service not found', $NotFoundStates[$OverrideNotFound]).Commit(); + + # The hidden metric package is attached only after this test, otherwise it would + # count as a check of an otherwise empty package. + if ($CheckPackage.HasChecks() -eq $false) { + if ($MitigateUnknown) { + return $CheckPackage.SetOk('No service matches the given filter', $true).Compile(); + } + + return $CheckPackage.SetError('No service matches the given filter').Compile(); + } + + if (-not $NoPerfData) { + foreach ($SummaryLabel in $SummaryCount.Keys) { + $MetricPackage.AddCheck( + (New-IcingaPlugin $SummaryLabel $SummaryCount[$SummaryLabel]).MetricIndex('summary').MetricLabel($SummaryLabel).CheckRange() + ).Commit(); + } + + $MetricPackage.AddCheck( + (New-IcingaPlugin 'count' $ServiceCount).MetricIndex('summary').MetricLabel('count').CheckRange() + ).Commit(); + + $CheckPackage.AddCheck($MetricPackage).Commit(); + } + + return $CheckPackage.Compile(); +} diff --git a/src/Plugins/Public/Invoke-IcingaCheckUptime.ps1 b/src/Plugins/Public/Invoke-IcingaCheckUptime.ps1 new file mode 100644 index 0000000..787c062 --- /dev/null +++ b/src/Plugins/Public/Invoke-IcingaCheckUptime.ps1 @@ -0,0 +1,111 @@ +<# +.SYNOPSIS +Check the time since the last system start against thresholds + +.DESCRIPTION +Reads the '\System\System Up Time' performance counter and builds a single +IcingaPlugin container named 'System Uptime: ' with the check 'System +Uptime' (whole seconds since the last start, shown as a duration such as +'1d 2h 3m 4s') and the informational 'Last Boot' entry with the start time. The +check is evaluated immediately against the warning and critical thresholds, which +accept durations with an Icinga time unit and the full Icinga range grammar: +'1d:' raises an alert while the system runs shorter than one day (a recent +reboot), '30d' while it runs longer than 30 days. + +The counter is declared through New-IcingaPerformanceCounter, so the +performance-counter daemon keeps it warm. A failed read is reported as UNKNOWN +with the counter error. + +Performance data uses the label 'windows::ifw_uptime::uptime' in seconds. + +.PARAMETER Warning +| Name | Type | Description | Default | +|---------|---------------|----------------------------------------------------------|---------| +| Warning | System.String | Warning threshold as duration or range, e.g. '1d:'. | | + +.PARAMETER Critical +| Name | Type | Description | Default | +|----------|---------------|----------------------------------------------------------|---------| +| Critical | System.String | Critical threshold as duration or range, e.g. '30m:'. | | + +.PARAMETER Verbosity +| Name | Type | Description | Default | +|-----------|--------------|-----------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | + +.PARAMETER NoPerfData +| Name | Type | Description | Default | +|------------|----------------------------------------------|---------------------------------------|---------| +| NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | + +.OUTPUTS +System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). + +.EXAMPLE +PS> Invoke-IcingaCheckUptime -Warning '1d:' -Critical '30m:' + +Warns during the first day after a reboot and goes critical during the first 30 minutes. + +.EXAMPLE +PS> Invoke-IcingaCheckUptime -Warning '60d' -Verbosity 2 + +Warns when the system has not been restarted for more than 60 days. + +.NOTES +Windows-only. Reads the '\System\System Up Time' performance counter; the user +needs read access to the performance counters ('Performance Monitor Users'). The +integer exit code is the return value; an Icinga command wrapper is expected to +exit with it. +#> +function Invoke-IcingaCheckUptime() +{ + param ( + [string]$Warning = '', + [string]$Critical = '', + [int]$Verbosity = 0, + [switch]$NoPerfData = $false + ); + + [string]$CounterPath = '\System\System Up Time'; + + # Literal declaration, so the counter discovery at module start finds and warms it. + New-IcingaPerformanceCounter -Counter @('\System\System Up Time'); + + $CheckPackage = New-IcingaPlugin 'System Uptime'; + $CheckPackage.Verbose = $Verbosity; + + $Counters = Get-IcingaPerformanceCounter -Counter $CounterPath -StructureByInstance; + $Value = $null; + + if ($null -ne $Counters -and $null -ne $Counters['System']) { + $Value = Get-IcingaPerformanceCounterValue -InputObject $Counters['System']['System Up Time']; + } + + if ($null -eq $Value -or $Value -is [string]) { + return $CheckPackage.SetError('Failed to read the performance counter {0}: {1}', $CounterPath, $Value).Compile(); + } + + [uint64]$Uptime = [System.Math]::Round([double]$Value, 0); + $CheckPackage.Name = [string]::Format('System Uptime: {0}', ('IcingaUnit' -as [type])::new([string]$Uptime, 's', '', $false).OutputString); + + $UptimeCheck = New-IcingaPlugin 'System Uptime' $Uptime 's'; + $UptimeCheck.NoPerfData = $NoPerfData; + + $CheckPackage.AddCheck( + $UptimeCheck. + MetricIndex('windows'). + MetricLabel('uptime'). + Warning($Warning). + Critical($Critical). + CheckRange() + ).Commit(); + + $BootCheck = New-IcingaPlugin 'Last Boot'; + $BootCheck.NoPerfData = $true; + + $CheckPackage.AddCheck( + $BootCheck.SetNotice([datetime]::Now.AddSeconds(-1 * [double]$Uptime).ToString('yyyy-MM-dd HH:mm:ss')) + ).Commit(); + + return $CheckPackage.Compile(); +} diff --git a/src/Provider/Disk/Public/Get-IcingaDiskInformation.ps1 b/src/Provider/Disk/Public/Get-IcingaDiskInformation.ps1 new file mode 100644 index 0000000..8caf3c9 --- /dev/null +++ b/src/Provider/Disk/Public/Get-IcingaDiskInformation.ps1 @@ -0,0 +1,303 @@ +<# +.SYNOPSIS +Collect correlated physical disk, partition, volume and MPIO data in one call + +.DESCRIPTION +Get-IcingaDiskInformation is the single data source for disk related plugins. It +reads every involved CIM class exactly once and correlates the results in +memory, instead of issuing one query per disk or volume, so the whole storage +picture is available in well below a second. The Entrypoint selects the view +that is returned and limits the queries to the classes that view needs: + +Volume returns the local disk volumes (Win32_Volume, DriveType 3) keyed by their +volume path ('\\?\Volume{GUID}\'), each with size, free and used space and the +disk and partition it lives on. Partition returns every partition +(MSFT_Partition) keyed by 'Disk #, Partition #', each with its +volume. PhysicalDisk returns every disk known to the operating system +(MSFT_Disk) keyed by its disk number, enriched with the media type +(MSFT_PhysicalDisk), its partitions, volumes and drive letters and, on hosts +with the MPIO feature, its multipath information (MPIO_DISK_INFO). + +All queries go through Get-IcingaWindowsInformation. When the main class of the +requested view cannot be read, the IcingaError of that query is returned instead +of the data; failures of enriching classes (for example MPIO on hosts without the +feature) only leave the related fields empty. Every exit goes through +Write-FunctionReturnValue with its own return code (DiskInformationCollected, +DiskInformationVolumeQueryFailed, DiskInformationPartitionQueryFailed, +DiskInformationDiskQueryFailed), so the log shows where the collection stopped. + +.PARAMETER Entrypoint +| Name | Type | Description | Default | +|------------|---------------|----------------------------------------------------------|--------------| +| Entrypoint | System.String | View to return: 'PhysicalDisk', 'Partition' or 'Volume'. | PhysicalDisk | + +.OUTPUTS +System.Collections.Hashtable — The entries of the requested view, or an +IcingaError when its main class could not be read. Entry fields per view: + +Volume: DeviceId, Name, DriveLetter ('C:' or ''), Label, FileSystem, Size, +FreeSpace, UsedSpace (bytes, $null when unknown), DiskNumber, PartitionNumber, +PartitionId. + +Partition: Id, DiskNumber, PartitionNumber, DriveLetter, Size, Offset, +GptType, MbrType, IsBoot, IsSystem, IsActive, IsHidden, AccessPaths, VolumeId, +Volume (the volume entry or $null). + +PhysicalDisk: Number, FriendlyName, Model, Manufacturer, SerialNumber, UniqueId, +Size, BusType, MediaType, SpindleSpeed, HealthStatus, OperationalStatus, +IsOffline, OfflineReason, IsReadOnly, IsBoot, IsSystem, IsClustered, +PartitionStyle, Location, Partitions (partition entries keyed by partition +number), Volumes (volume entries), DriveLetters, MPIO (Name, InstanceName, +NumberPaths, or $null). Status values are the raw numeric codes of the +MSFT_Disk / MSFT_PhysicalDisk classes. + +.EXAMPLE +PS> (Get-IcingaDiskInformation -Entrypoint 'Volume').Values | Select-Object Name, Size, FreeSpace + +Lists the size and free space of every local volume. + +.EXAMPLE +PS> $Disks = Get-IcingaDiskInformation +PS> $Disks['0'].DriveLetters + +Returns the drive letters of disk 0. + +.NOTES +Windows-only. Reads root/cimv2 (Win32_Volume), root/Microsoft/Windows/Storage +(MSFT_Disk, MSFT_PhysicalDisk, MSFT_Partition) and root/wmi (MPIO_DISK_INFO). +Standard users can read all of them. Spanned volumes are linked to the first +partition reporting them. +#> +function Get-IcingaDiskInformation() +{ + param ( + [ValidateSet('PhysicalDisk', 'Partition', 'Volume')] + [string]$Entrypoint = 'PhysicalDisk' + ); + + [string]$StorageNamespace = 'root/Microsoft/Windows/Storage'; + + $Volumes = Get-IcingaWindowsInformation -ClassName 'Win32_Volume' -Filter 'DriveType = 3' -Property 'DeviceID', 'Name', 'DriveLetter', 'Label', 'FileSystem', 'Capacity', 'FreeSpace'; + + if (Test-IcingaError -InputObject $Volumes) { + if ($Entrypoint -eq 'Volume') { + return (Write-FunctionReturnValue -ReturnValue 'DiskInformationVolumeQueryFailed' -Data @{ 'Entrypoint' = $Entrypoint; 'Error' = $Volumes.Message; } -OverrideReturn $Volumes); + } + + $Volumes = @(); + } + + [hashtable]$VolumeData = @{ }; + + foreach ($Volume in $Volumes) { + $Size = $null; + $FreeSpace = $null; + $UsedSpace = $null; + + if ($null -ne $Volume.Capacity) { + $Size = [uint64]$Volume.Capacity; + } + + if ($null -ne $Volume.FreeSpace) { + $FreeSpace = [uint64]$Volume.FreeSpace; + } + + if ($null -ne $Size -and $null -ne $FreeSpace -and $FreeSpace -le $Size) { + $UsedSpace = $Size - $FreeSpace; + } + + $VolumeData[[string]$Volume.DeviceID] = @{ + 'DeviceId' = [string]$Volume.DeviceID; + 'Name' = [string]$Volume.Name; + 'DriveLetter' = [string]$Volume.DriveLetter; + 'Label' = [string]$Volume.Label; + 'FileSystem' = [string]$Volume.FileSystem; + 'Size' = $Size; + 'FreeSpace' = $FreeSpace; + 'UsedSpace' = $UsedSpace; + 'DiskNumber' = $null; + 'PartitionNumber' = $null; + 'PartitionId' = $null; + }; + } + + $Partitions = Get-IcingaWindowsInformation -ClassName 'MSFT_Partition' -Namespace $StorageNamespace -Property 'DiskNumber', 'PartitionNumber', 'DriveLetter', 'AccessPaths', 'Size', 'Offset', 'GptType', 'MbrType', 'IsBoot', 'IsSystem', 'IsActive', 'IsHidden'; + + if (Test-IcingaError -InputObject $Partitions) { + if ($Entrypoint -ne 'Volume') { + return (Write-FunctionReturnValue -ReturnValue 'DiskInformationPartitionQueryFailed' -Data @{ 'Entrypoint' = $Entrypoint; 'Error' = $Partitions.Message; } -OverrideReturn $Partitions); + } + + # The volume view stays usable without the disk mapping. + $Partitions = @(); + } + + [hashtable]$PartitionData = @{ }; + + foreach ($Partition in $Partitions) { + [string]$PartitionId = [string]::Format('Disk #{0}, Partition #{1}', $Partition.DiskNumber, $Partition.PartitionNumber); + [string]$DriveLetter = ''; + + # MSFT_Partition reports a partition without drive letter as the NUL character. + if ($null -ne $Partition.DriveLetter -and [int][char]$Partition.DriveLetter -ne 0) { + $DriveLetter = [string]::Format('{0}:', $Partition.DriveLetter); + } + + $Entry = @{ + 'Id' = $PartitionId; + 'DiskNumber' = [int]$Partition.DiskNumber; + 'PartitionNumber' = [int]$Partition.PartitionNumber; + 'DriveLetter' = $DriveLetter; + 'Size' = [uint64]$Partition.Size; + 'Offset' = [uint64]$Partition.Offset; + 'GptType' = [string]$Partition.GptType; + 'MbrType' = $Partition.MbrType; + 'IsBoot' = [bool]$Partition.IsBoot; + 'IsSystem' = [bool]$Partition.IsSystem; + 'IsActive' = [bool]$Partition.IsActive; + 'IsHidden' = [bool]$Partition.IsHidden; + 'AccessPaths' = @($Partition.AccessPaths); + 'VolumeId' = $null; + 'Volume' = $null; + }; + + foreach ($AccessPath in $Entry.AccessPaths) { + if ($VolumeData.ContainsKey([string]$AccessPath) -eq $false) { + continue; + } + + $LinkedVolume = $VolumeData[[string]$AccessPath]; + + $Entry.VolumeId = $LinkedVolume.DeviceId; + $Entry.Volume = $LinkedVolume; + + if ($null -eq $LinkedVolume.PartitionId) { + $LinkedVolume.DiskNumber = $Entry.DiskNumber; + $LinkedVolume.PartitionNumber = $Entry.PartitionNumber; + $LinkedVolume.PartitionId = $PartitionId; + } + + break; + } + + $PartitionData[$PartitionId] = $Entry; + } + + if ($Entrypoint -eq 'Volume') { + return (Write-FunctionReturnValue -ReturnValue 'DiskInformationCollected' -Data @{ 'Entrypoint' = $Entrypoint; 'Count' = $VolumeData.Count; } -OverrideReturn $VolumeData); + } + + if ($Entrypoint -eq 'Partition') { + return (Write-FunctionReturnValue -ReturnValue 'DiskInformationCollected' -Data @{ 'Entrypoint' = $Entrypoint; 'Count' = $PartitionData.Count; } -OverrideReturn $PartitionData); + } + + $Disks = Get-IcingaWindowsInformation -ClassName 'MSFT_Disk' -Namespace $StorageNamespace -Property 'Number', 'FriendlyName', 'Model', 'Manufacturer', 'SerialNumber', 'UniqueId', 'Size', 'BusType', 'HealthStatus', 'OperationalStatus', 'IsOffline', 'OfflineReason', 'IsReadOnly', 'IsBoot', 'IsSystem', 'IsClustered', 'PartitionStyle', 'Location'; + + if (Test-IcingaError -InputObject $Disks) { + return (Write-FunctionReturnValue -ReturnValue 'DiskInformationDiskQueryFailed' -Data @{ 'Entrypoint' = $Entrypoint; 'Error' = $Disks.Message; } -OverrideReturn $Disks); + } + + [hashtable]$PhysicalDiskData = @{ }; + $PhysicalDisks = Get-IcingaWindowsInformation -ClassName 'MSFT_PhysicalDisk' -Namespace $StorageNamespace -Property 'DeviceId', 'MediaType', 'SpindleSpeed'; + + if ((Test-IcingaError -InputObject $PhysicalDisks) -eq $false) { + foreach ($PhysicalDisk in $PhysicalDisks) { + $PhysicalDiskData[[string]$PhysicalDisk.DeviceId] = $PhysicalDisk; + } + } + + [hashtable]$MpioData = @{ }; + $MpioDisks = Get-IcingaWindowsInformation -ClassName 'MPIO_DISK_INFO' -Namespace 'root/wmi'; + + if ((Test-IcingaError -InputObject $MpioDisks) -eq $false) { + foreach ($MpioDisk in $MpioDisks) { + foreach ($Drive in $MpioDisk.DriveInfo) { + if ([string]::IsNullOrEmpty([string]$Drive.SerialNumber)) { + continue; + } + + $MpioData[([string]$Drive.SerialNumber).Trim()] = @{ + 'Name' = [string]$Drive.Name; + 'InstanceName' = [string]$MpioDisk.InstanceName; + 'NumberPaths' = [int]$Drive.NumberPaths; + }; + } + } + } + + [hashtable]$DiskData = @{ }; + + foreach ($Disk in $Disks) { + [string]$DiskNumber = [string]$Disk.Number; + [string]$SerialNumber = ([string]$Disk.SerialNumber).Trim(); + [string]$UniqueId = [string]$Disk.UniqueId; + $PhysicalDisk = $PhysicalDiskData[$DiskNumber]; + $Mpio = $null; + + if ($MpioData.ContainsKey($UniqueId)) { + $Mpio = $MpioData[$UniqueId]; + } elseif ([string]::IsNullOrEmpty($SerialNumber) -eq $false -and $MpioData.ContainsKey($SerialNumber)) { + $Mpio = $MpioData[$SerialNumber]; + } + + $Entry = @{ + 'Number' = [int]$Disk.Number; + 'FriendlyName' = [string]$Disk.FriendlyName; + 'Model' = [string]$Disk.Model; + 'Manufacturer' = [string]$Disk.Manufacturer; + 'SerialNumber' = $SerialNumber; + 'UniqueId' = $UniqueId; + 'Size' = [uint64]$Disk.Size; + 'BusType' = $Disk.BusType; + 'MediaType' = $null; + 'SpindleSpeed' = $null; + 'HealthStatus' = $Disk.HealthStatus; + 'OperationalStatus' = @($Disk.OperationalStatus); + 'IsOffline' = [bool]$Disk.IsOffline; + 'OfflineReason' = $Disk.OfflineReason; + 'IsReadOnly' = [bool]$Disk.IsReadOnly; + 'IsBoot' = [bool]$Disk.IsBoot; + 'IsSystem' = [bool]$Disk.IsSystem; + 'IsClustered' = [bool]$Disk.IsClustered; + 'PartitionStyle' = $Disk.PartitionStyle; + 'Location' = [string]$Disk.Location; + 'Partitions' = @{ }; + 'Volumes' = @(); + 'DriveLetters' = @(); + 'MPIO' = $Mpio; + }; + + if ($null -ne $PhysicalDisk) { + $Entry.MediaType = $PhysicalDisk.MediaType; + $Entry.SpindleSpeed = $PhysicalDisk.SpindleSpeed; + } + + $DiskData[$DiskNumber] = $Entry; + } + + foreach ($Partition in $PartitionData.Values) { + [string]$DiskNumber = [string]$Partition.DiskNumber; + + if ($DiskData.ContainsKey($DiskNumber) -eq $false) { + continue; + } + + $Entry = $DiskData[$DiskNumber]; + $Entry.Partitions[[string]$Partition.PartitionNumber] = $Partition; + + if ([string]::IsNullOrEmpty($Partition.DriveLetter) -eq $false) { + $Entry.DriveLetters += $Partition.DriveLetter; + } + + if ($null -ne $Partition.Volume) { + $Entry.Volumes += $Partition.Volume; + } + } + + foreach ($Entry in $DiskData.Values) { + $Entry.DriveLetters = ConvertTo-IcingaSortedArray -InputObject $Entry.DriveLetters; + $Entry.Volumes = ConvertTo-IcingaSortedArray -InputObject $Entry.Volumes -Property 'Name'; + } + + return (Write-FunctionReturnValue -ReturnValue 'DiskInformationCollected' -Data @{ 'Entrypoint' = $Entrypoint; 'Count' = $DiskData.Count; } -OverrideReturn $DiskData); +} diff --git a/src/Provider/FileSystem/Public/Get-IcingaDirectoryInformation.ps1 b/src/Provider/FileSystem/Public/Get-IcingaDirectoryInformation.ps1 new file mode 100644 index 0000000..7b50ef9 --- /dev/null +++ b/src/Provider/FileSystem/Public/Get-IcingaDirectoryInformation.ps1 @@ -0,0 +1,434 @@ +<# +.SYNOPSIS +Collect file and folder statistics of a directory in a single pass + +.DESCRIPTION +Get-IcingaDirectoryInformation is the data source of the directory plugin. It +reads the directory exactly once and evaluates every entry while it is read: the +name filter, the time and size filters and the statistics (counts, total, +smallest, largest and average size) are all handled in the same loop, without a +pipeline, without script blocks and without a second lookup per entry. + +All filter values are converted once before the scan. Time filters accept a +duration with an Icinga time unit ('20d', '12h', '30m', a plain number counts as +seconds) and compare against the moment of the call: ChangeOlderThan '20d' keeps +entries last written more than 20 days ago, ChangeYoungerThan keeps the ones +written within the last 20 days and ChangeTimeEqual keeps the ones written on +the calendar day 20 days ago. The Creation* and Access* filters do the same for +the creation and last access time. Size filters accept a size ('20MB', '1.5GiB', +a plain number counts as bytes) and only ever match files. Every given filter must +match (they are combined with AND). + +FileNames are wildcard patterns matched case-insensitively against the entry +name; an entry is kept when any pattern matches. With Recurse the scan descends +into every subdirectory, whether its name matches or not. Hidden and system +entries are skipped like Get-ChildItem without -Force does, and reparse points +(junctions, symbolic links) are counted but never followed, so the scan cannot +loop. + +Every exit goes through Write-FunctionReturnValue with its own return code +(DirectoryInformationCollected, DirectoryPathMissing, DirectoryPathNotFound, +DirectoryAccessDenied, DirectoryFilterInvalid, DirectoryReadFailed). A failure +returns an IcingaError that names the directory or filter, so a plugin can stop +with one check. A directory that cannot be read, including a subdirectory during +a recursive scan, ends the scan with DirectoryAccessDenied or DirectoryReadFailed. + +.PARAMETER Path +| Name | Type | Description | Default | +|------|---------------|-----------------------------------------------|---------| +| Path | System.String | Directory to scan, e.g. 'C:\ProgramData\Logs'. | | + +.PARAMETER FileNames +| Name | Type | Description | Default | +|-----------|--------------|----------------------------------------------------------|---------| +| FileNames | System.Array | Wildcard patterns for the entry names, e.g. '*.log'. | @('*') | + +.PARAMETER Recurse +| Name | Type | Description | Default | +|---------|----------------------------------------------|--------------------------------------|---------| +| Recurse | System.Management.Automation.SwitchParameter | Scan every subdirectory as well. | False | + +.PARAMETER ChangeTimeEqual +| Name | Type | Description | Default | +|-----------------|---------------|---------------------------------------------------------------|---------| +| ChangeTimeEqual | System.String | Keep entries last written on the day this long ago, e.g. '1d'. | | + +.PARAMETER ChangeYoungerThan +| Name | Type | Description | Default | +|-------------------|---------------|-----------------------------------------------------------|---------| +| ChangeYoungerThan | System.String | Keep entries last written within this duration, e.g. '5d'. | | + +.PARAMETER ChangeOlderThan +| Name | Type | Description | Default | +|-----------------|---------------|----------------------------------------------------------------|---------| +| ChangeOlderThan | System.String | Keep entries last written longer ago than this, e.g. '10d'. | | + +.PARAMETER CreationTimeEqual +| Name | Type | Description | Default | +|-------------------|---------------|-----------------------------------------------------------|---------| +| CreationTimeEqual | System.String | Keep entries created on the day this long ago, e.g. '1d'. | | + +.PARAMETER CreationYoungerThan +| Name | Type | Description | Default | +|---------------------|---------------|------------------------------------------------------|---------| +| CreationYoungerThan | System.String | Keep entries created within this duration, e.g. '5d'. | | + +.PARAMETER CreationOlderThan +| Name | Type | Description | Default | +|-------------------|---------------|----------------------------------------------------------|---------| +| CreationOlderThan | System.String | Keep entries created longer ago than this, e.g. '10d'. | | + +.PARAMETER AccessYoungerThan +| Name | Type | Description | Default | +|-------------------|---------------|------------------------------------------------------------|---------| +| AccessYoungerThan | System.String | Keep entries last accessed within this duration, e.g. '5d'. | | + +.PARAMETER AccessOlderThan +| Name | Type | Description | Default | +|-----------------|---------------|---------------------------------------------------------------|---------| +| AccessOlderThan | System.String | Keep entries last accessed longer ago than this, e.g. '10d'. | | + +.PARAMETER FileSizeGreaterThan +| Name | Type | Description | Default | +|---------------------|---------------|-----------------------------------------------|---------| +| FileSizeGreaterThan | System.String | Keep files larger than this size, e.g. '20MB'. | | + +.PARAMETER FileSizeSmallerThan +| Name | Type | Description | Default | +|---------------------|---------------|-----------------------------------------------|---------| +| FileSizeSmallerThan | System.String | Keep files smaller than this size, e.g. '5MB'. | | + +.PARAMETER IncludeFileList +| Name | Type | Description | Default | +|-----------------|----------------------------------------------|------------------------------------------------------|---------| +| IncludeFileList | System.Management.Automation.SwitchParameter | Also return every kept entry in FileList. | False | + +.PARAMETER IgnoreMissingPath +| Name | Type | Description | Default | +|-------------------|----------------------------------------------|------------------------------------------------------------|---------| +| IgnoreMissingPath | System.Management.Automation.SwitchParameter | Return an empty result instead of an error for a missing path. | False | + +.OUTPUTS +System.Collections.Hashtable — Path, Exists, FileCount, FolderCount, TotalCount, +TotalSize, LargestFile, SmallestFile and AverageSize (sizes in bytes, the smallest +file is 0 when no file was kept) and FileList (the kept System.IO.FileSystemInfo +entries, empty unless IncludeFileList is set). Returns an IcingaError on failure. + +.EXAMPLE +PS> Get-IcingaDirectoryInformation -Path 'C:\Backup' -FileNames '*.bak' -ChangeYoungerThan '1d' + +Counts the backup files written within the last day. + +.EXAMPLE +PS> Get-IcingaDirectoryInformation -Path 'D:\Logs' -Recurse -FileSizeGreaterThan '100MB' -IncludeFileList + +Returns every log file larger than 100MB below D:\Logs together with the statistics. + +.NOTES +Reads the file system through System.IO.DirectoryInfo; the user needs list +permission on every scanned directory. Relative paths are resolved against the +current PowerShell file system location. No external services are used. +#> +function Get-IcingaDirectoryInformation() +{ + param ( + [string]$Path = '', + [array]$FileNames = @( '*' ), + [switch]$Recurse = $false, + [string]$ChangeTimeEqual = '', + [string]$ChangeYoungerThan = '', + [string]$ChangeOlderThan = '', + [string]$CreationTimeEqual = '', + [string]$CreationYoungerThan = '', + [string]$CreationOlderThan = '', + [string]$AccessYoungerThan = '', + [string]$AccessOlderThan = '', + [string]$FileSizeGreaterThan = '', + [string]$FileSizeSmallerThan = '', + [switch]$IncludeFileList = $false, + [switch]$IgnoreMissingPath = $false + ); + + if ([string]::IsNullOrEmpty($Path)) { + return (Write-FunctionReturnValue -ReturnValue 'DirectoryPathMissing' -Data @{ } -OverrideReturn (('IcingaError' -as [type])::new('DirectoryPathMissing', 'No directory path was provided', @{ }))); + } + + # Every filter value is converted once, so the scan only compares against fixed limits. + [hashtable]$Limits = @{ }; + + foreach ($Filter in @( + @('ChangeTimeEqual', $ChangeTimeEqual, 'Time'), + @('ChangeYoungerThan', $ChangeYoungerThan, 'Time'), + @('ChangeOlderThan', $ChangeOlderThan, 'Time'), + @('CreationTimeEqual', $CreationTimeEqual, 'Time'), + @('CreationYoungerThan', $CreationYoungerThan, 'Time'), + @('CreationOlderThan', $CreationOlderThan, 'Time'), + @('AccessYoungerThan', $AccessYoungerThan, 'Time'), + @('AccessOlderThan', $AccessOlderThan, 'Time'), + @('FileSizeGreaterThan', $FileSizeGreaterThan, 'Data'), + @('FileSizeSmallerThan', $FileSizeSmallerThan, 'Data') + )) { + if ([string]::IsNullOrEmpty($Filter[1])) { + continue; + } + + [string]$DefaultUnit = 's'; + + if ($Filter[2] -eq 'Data') { + $DefaultUnit = 'B'; + } + + $Unit = ConvertTo-IcingaUnit -InputValue $Filter[1] -InputUnit $DefaultUnit; + + if ($null -eq $Unit -or $Unit.Family -ne $Filter[2]) { + [string]$Expected = 'duration such as 20d, 12h or 30m'; + + if ($Filter[2] -eq 'Data') { + $Expected = 'size such as 20MB or 1.5GiB'; + } + + [hashtable]$ErrorData = @{ 'Path' = $Path; 'Filter' = $Filter[0]; 'Value' = $Filter[1]; }; + + return (Write-FunctionReturnValue -ReturnValue 'DirectoryFilterInvalid' -Data $ErrorData -OverrideReturn (('IcingaError' -as [type])::new('DirectoryFilterInvalid', [string]::Format('The value "{0}" of -{1} is not a valid {2}', $Filter[1], $Filter[0], $Expected), $ErrorData))); + } + + $Limits[$Filter[0]] = [System.Math]::Abs([double]$Unit.BaseValue); + } + + [datetime]$Now = [datetime]::Now; + $ChangeDay = $null; + $ChangeAfter = $null; + $ChangeBefore = $null; + $CreationDay = $null; + $CreationAfter = $null; + $CreationBefore = $null; + $AccessAfter = $null; + $AccessBefore = $null; + $SizeAbove = $null; + $SizeBelow = $null; + + if ($Limits.ContainsKey('ChangeTimeEqual')) { + $ChangeDay = $Now.AddSeconds(-$Limits['ChangeTimeEqual']).Date; + } + if ($Limits.ContainsKey('ChangeYoungerThan')) { + $ChangeAfter = $Now.AddSeconds(-$Limits['ChangeYoungerThan']); + } + if ($Limits.ContainsKey('ChangeOlderThan')) { + $ChangeBefore = $Now.AddSeconds(-$Limits['ChangeOlderThan']); + } + if ($Limits.ContainsKey('CreationTimeEqual')) { + $CreationDay = $Now.AddSeconds(-$Limits['CreationTimeEqual']).Date; + } + if ($Limits.ContainsKey('CreationYoungerThan')) { + $CreationAfter = $Now.AddSeconds(-$Limits['CreationYoungerThan']); + } + if ($Limits.ContainsKey('CreationOlderThan')) { + $CreationBefore = $Now.AddSeconds(-$Limits['CreationOlderThan']); + } + if ($Limits.ContainsKey('AccessYoungerThan')) { + $AccessAfter = $Now.AddSeconds(-$Limits['AccessYoungerThan']); + } + if ($Limits.ContainsKey('AccessOlderThan')) { + $AccessBefore = $Now.AddSeconds(-$Limits['AccessOlderThan']); + } + if ($Limits.ContainsKey('FileSizeGreaterThan')) { + $SizeAbove = [long]$Limits['FileSizeGreaterThan']; + } + if ($Limits.ContainsKey('FileSizeSmallerThan')) { + $SizeBelow = [long]$Limits['FileSizeSmallerThan']; + } + + [bool]$HasChangeFilter = ($null -ne $ChangeDay -or $null -ne $ChangeAfter -or $null -ne $ChangeBefore); + [bool]$HasCreationFilter = ($null -ne $CreationDay -or $null -ne $CreationAfter -or $null -ne $CreationBefore); + [bool]$HasAccessFilter = ($null -ne $AccessAfter -or $null -ne $AccessBefore); + [bool]$HasSizeFilter = ($null -ne $SizeAbove -or $null -ne $SizeBelow); + + [bool]$MatchAll = ($FileNames.Count -eq 0); + [array]$Patterns = @(); + + foreach ($Name in $FileNames) { + if ([string]$Name -eq '*') { + $MatchAll = $true; + break; + } + + $Patterns += [System.Management.Automation.WildcardPattern]::new([string]$Name, [System.Management.Automation.WildcardOptions]::IgnoreCase); + } + + if (-not [System.IO.Path]::IsPathRooted($Path)) { + $Path = Join-Path -Path (Get-Location -PSProvider 'FileSystem').ProviderPath -ChildPath $Path; + } + + [hashtable]$Result = @{ + 'Path' = $Path; + 'Exists' = $false; + 'FileCount' = 0; + 'FolderCount' = 0; + 'TotalCount' = 0; + 'TotalSize' = [long]0; + 'LargestFile' = [long]0; + 'SmallestFile' = [long]0; + 'AverageSize' = [double]0; + 'FileList' = @(); + }; + + try { + $Root = [System.IO.DirectoryInfo]::new($Path); + [bool]$RootExists = $Root.Exists; + } catch { + [hashtable]$ErrorData = @{ 'Path' = $Path; 'Error' = $_.Exception.Message; }; + + return (Write-FunctionReturnValue -ReturnValue 'DirectoryReadFailed' -Data $ErrorData -OverrideReturn (('IcingaError' -as [type])::new('DirectoryReadFailed', [string]::Format('The directory "{0}" could not be read: {1}', $Path, $_.Exception.Message), $ErrorData))); + } + + if (-not $RootExists) { + if ($IgnoreMissingPath) { + return (Write-FunctionReturnValue -ReturnValue 'DirectoryInformationCollected' -Data @{ 'Path' = $Path; 'Exists' = $false; } -OverrideReturn $Result); + } + + [hashtable]$ErrorData = @{ 'Path' = $Path; }; + + return (Write-FunctionReturnValue -ReturnValue 'DirectoryPathNotFound' -Data $ErrorData -OverrideReturn (('IcingaError' -as [type])::new('DirectoryPathNotFound', [string]::Format('The directory "{0}" does not exist on this system', $Path), $ErrorData))); + } + + [System.IO.FileAttributes]$SkipAttributes = [System.IO.FileAttributes]::Hidden -bor [System.IO.FileAttributes]::System; + [System.IO.FileAttributes]$ReparsePoint = [System.IO.FileAttributes]::ReparsePoint; + + $Pending = New-Object 'System.Collections.Generic.Stack[System.IO.DirectoryInfo]'; + $FileList = New-Object 'System.Collections.Generic.List[System.IO.FileSystemInfo]'; + + [int]$FileCount = 0; + [int]$FolderCount = 0; + [long]$TotalSize = 0; + [long]$LargestFile = 0; + [long]$SmallestFile = -1; + + $Pending.Push($Root); + + while ($Pending.Count -ne 0) { + $Directory = $Pending.Pop(); + + try { + foreach ($Entry in $Directory.EnumerateFileSystemInfos()) { + if (($Entry.Attributes -band $SkipAttributes) -ne 0) { + continue; + } + + [bool]$IsDirectory = ($Entry -is [System.IO.DirectoryInfo]); + + # Subdirectories are scanned whether their own name matches or not. + if ($IsDirectory -and $Recurse -and ($Entry.Attributes -band $ReparsePoint) -eq 0) { + $Pending.Push($Entry); + } + + if (-not $MatchAll) { + [bool]$Matched = $false; + + foreach ($Pattern in $Patterns) { + if ($Pattern.IsMatch($Entry.Name)) { + $Matched = $true; + break; + } + } + + if (-not $Matched) { + continue; + } + } + + if ($HasChangeFilter) { + [datetime]$Changed = $Entry.LastWriteTime; + + if (($null -ne $ChangeDay -and $Changed.Date -ne $ChangeDay) -or ($null -ne $ChangeAfter -and $Changed -le $ChangeAfter) -or ($null -ne $ChangeBefore -and $Changed -ge $ChangeBefore)) { + continue; + } + } + + if ($HasCreationFilter) { + [datetime]$Created = $Entry.CreationTime; + + if (($null -ne $CreationDay -and $Created.Date -ne $CreationDay) -or ($null -ne $CreationAfter -and $Created -le $CreationAfter) -or ($null -ne $CreationBefore -and $Created -ge $CreationBefore)) { + continue; + } + } + + if ($HasAccessFilter) { + [datetime]$Accessed = $Entry.LastAccessTime; + + if (($null -ne $AccessAfter -and $Accessed -le $AccessAfter) -or ($null -ne $AccessBefore -and $Accessed -ge $AccessBefore)) { + continue; + } + } + + if ($IsDirectory) { + # A size filter only ever matches files. + if ($HasSizeFilter) { + continue; + } + + $FolderCount += 1; + } else { + [long]$Length = $Entry.Length; + + if ($HasSizeFilter -and (($null -ne $SizeAbove -and $Length -le $SizeAbove) -or ($null -ne $SizeBelow -and $Length -ge $SizeBelow))) { + continue; + } + + $FileCount += 1; + $TotalSize += $Length; + + if ($Length -gt $LargestFile) { + $LargestFile = $Length; + } + + if ($SmallestFile -lt 0 -or $Length -lt $SmallestFile) { + $SmallestFile = $Length; + } + } + + if ($IncludeFileList) { + $FileList.Add($Entry); + } + } + } catch { + # PowerShell may wrap an exception thrown while enumerating, so the cause is + # searched in the whole exception chain. + [string]$ReturnCode = 'DirectoryReadFailed'; + [string]$Message = [string]::Format('The directory "{0}" could not be read: {1}', $Directory.FullName, $_.Exception.Message); + $Exception = $_.Exception; + + while ($null -ne $Exception) { + if ($Exception -is [System.UnauthorizedAccessException] -or $Exception -is [System.Security.SecurityException]) { + $ReturnCode = 'DirectoryAccessDenied'; + $Message = [string]::Format('Access to the directory "{0}" was denied', $Directory.FullName); + break; + } + + $Exception = $Exception.InnerException; + } + + [hashtable]$ErrorData = @{ 'Path' = $Path; 'Directory' = $Directory.FullName; 'Error' = $_.Exception.Message; }; + + return (Write-FunctionReturnValue -ReturnValue $ReturnCode -Data $ErrorData -OverrideReturn (('IcingaError' -as [type])::new($ReturnCode, $Message, $ErrorData))); + } + } + + if ($SmallestFile -lt 0) { + $SmallestFile = 0; + } + + $Result['Exists'] = $true; + $Result['FileCount'] = $FileCount; + $Result['FolderCount'] = $FolderCount; + $Result['TotalCount'] = $FileCount + $FolderCount; + $Result['TotalSize'] = $TotalSize; + $Result['LargestFile'] = $LargestFile; + $Result['SmallestFile'] = $SmallestFile; + $Result['FileList'] = $FileList.ToArray(); + + if ($FileCount -ne 0) { + $Result['AverageSize'] = [System.Math]::Round($TotalSize / $FileCount, 2); + } + + return (Write-FunctionReturnValue -ReturnValue 'DirectoryInformationCollected' -Data @{ 'Path' = $Path; 'FileCount' = $FileCount; 'FolderCount' = $FolderCount; } -OverrideReturn $Result); +} diff --git a/src/Tools/Private/Test-ModuleWildcardMatch.ps1 b/src/Tools/Private/Test-ModuleWildcardMatch.ps1 new file mode 100644 index 0000000..2d688e6 --- /dev/null +++ b/src/Tools/Private/Test-ModuleWildcardMatch.ps1 @@ -0,0 +1,44 @@ +<# +.SYNOPSIS +Test a string against a single wildcard pattern without throwing + +.DESCRIPTION +Compares the value case-insensitively with a wildcard pattern ('*', '?', +'[a-z]'). An invalid pattern, such as an unclosed '[', is logged through +Write-FunctionReturnValue (ArrayFilterInvalidPattern) and counts as no match, so +a broken filter argument never aborts a plugin. + +.PARAMETER Value +| Name | Type | Description | Default | +|-------|---------------|----------------------|---------| +| Value | System.String | The value to test. | | + +.PARAMETER Pattern +| Name | Type | Description | Default | +|---------|---------------|----------------------------|---------| +| Pattern | System.String | Wildcard pattern to match. | | + +.OUTPUTS +System.Boolean — True when the value matches the pattern. + +.EXAMPLE +PS> Test-ModuleWildcardMatch -Value 'Spooler' -Pattern 'spo*' + +Returns $true. + +.NOTES +Internal helper of Test-IcingaArrayFilter. +#> +function Test-ModuleWildcardMatch() +{ + param ( + [string]$Value = '', + [string]$Pattern = '' + ); + + try { + return ($Value -like $Pattern); + } catch { + return (Write-FunctionReturnValue -ReturnValue 'ArrayFilterInvalidPattern' -Data @{ 'Value' = $Value; 'Pattern' = $Pattern; 'Error' = $_.Exception.Message; } -OverrideReturn $false); + } +} diff --git a/src/Tools/Public/ConvertTo-IcingaSortedArray.ps1 b/src/Tools/Public/ConvertTo-IcingaSortedArray.ps1 new file mode 100644 index 0000000..66f0646 --- /dev/null +++ b/src/Tools/Public/ConvertTo-IcingaSortedArray.ps1 @@ -0,0 +1,91 @@ +<# +.SYNOPSIS +Sort objects by one or more properties in natural order without a script block + +.DESCRIPTION +ConvertTo-IcingaSortedArray sorts an array without Sort-Object and without any +script block, so the plugins stay usable in JEA sessions. Every element gets a +sort key from IcingaSortKey once, then the native [Array]::Sort orders keys and +elements with an ordinal string comparison, which keeps the sort fast for large +inputs such as all Windows services. + +The objects are compared by the given properties in order of precedence, or by +themselves when no property is given. Values sort in natural order: numbers +numerically and strings case-insensitively with digit runs compared by value, +so '0,2' comes before '0,10' and '_Total' after every numbered instance. The +sort is stable, equal elements keep their input order in both directions. +Hashtables are read by key, every other object (including CIM instances) by +member name. + +.PARAMETER InputObject +| Name | Type | Description | Default | +|-------------|--------------|------------------------|---------| +| InputObject | System.Array | The elements to sort. | @() | + +.PARAMETER Property +| Name | Type | Description | Default | +|----------|--------------|-------------------------------------------------------------|---------| +| Property | System.Array | Properties to sort by, in order of precedence; empty sorts the elements. | @() | + +.PARAMETER Descending +| Name | Type | Description | Default | +|------------|----------------------------------------------|-------------------------------|---------| +| Descending | System.Management.Automation.SwitchParameter | Sort in descending order. | False | + +.OUTPUTS +System.Object[] — A new array with the sorted elements; the input stays unchanged. + +.EXAMPLE +PS> ConvertTo-IcingaSortedArray -InputObject @('0,10', '_Total', '0,2', '0,_Total') + +Returns @('0,2', '0,10', '0,_Total', '_Total'). + +.EXAMPLE +PS> ConvertTo-IcingaSortedArray -InputObject $Services -Property 'Name' + +Sorts Win32_Service instances by their name. + +.NOTES +No external dependencies. Replaces 'Sort-Object -Property { ... }' in plugin +code. The verb follows the approved PowerShell verbs; 'Sort' is not one of them. +#> +function ConvertTo-IcingaSortedArray() +{ + param ( + [array]$InputObject = @(), + [array]$Property = @(), + [switch]$Descending = $false + ); + + if ($null -eq $InputObject -or $InputObject.Count -eq 0) { + return ,@(); + } + + [int]$Count = $InputObject.Count; + [string[]]$Keys = [string[]]::new($Count); + [object[]]$Items = [object[]]::new($Count); + $SortKeyType = 'IcingaSortKey' -as [type]; + + for ($i = 0; $i -lt $Count; $i++) { + # The position breaks ties and keeps the sort stable. A descending sort runs + # ascending and is reversed afterwards, so it needs the mirrored position. + [int]$Position = $i; + + if ($Descending) { + $Position = $Count - 1 - $i; + } + + $Keys[$i] = $SortKeyType::FromObject($InputObject[$i], [string[]]$Property) + $SortKeyType::Separator + $Position.ToString('0000000000'); + $Items[$i] = $InputObject[$i]; + } + + # The explicit casts select the non-generic overload; with the generic one + # PowerShell sorts a converted copy of the elements and leaves $Items unsorted. + [System.Array]::Sort([System.Array]$Keys, [System.Array]$Items, [System.Collections.IComparer][System.StringComparer]::Ordinal); + + if ($Descending) { + [System.Array]::Reverse($Items); + } + + return ,$Items; +} diff --git a/src/Tools/Public/Get-IcingaWindowsInformation.ps1 b/src/Tools/Public/Get-IcingaWindowsInformation.ps1 new file mode 100644 index 0000000..fa33c35 --- /dev/null +++ b/src/Tools/Public/Get-IcingaWindowsInformation.ps1 @@ -0,0 +1,129 @@ +<# +.SYNOPSIS +Query a CIM class and return its instances or an IcingaError + +.DESCRIPTION +Get-IcingaWindowsInformation is the single entry point for reading Windows +management data. It runs Get-CimInstance with -ErrorAction Stop and never +throws: on success it returns the instances as an array (empty when nothing +matches), on failure it returns an IcingaError that names the class, the +namespace and the reason, so a plugin can stop with one check: + + if (Test-IcingaError -InputObject $Data) { return $CheckPackage.SetError($Data).Compile(); } + +Every exit goes through Write-FunctionReturnValue with its own return code, so +the log shows exactly which query succeeded or failed and why: a successful +query (WindowsInformationQueried), a missing class name +(WindowsInformationClassNameMissing), an unknown class +(WindowsInformationClassUnknown), an unknown namespace +(WindowsInformationNamespaceInvalid), missing permissions +(WindowsInformationAccessDenied), an invalid filter or property list +(WindowsInformationInvalidQuery) and every other error +(WindowsInformationQueryFailed). The return code of a failure is also stored in +the ReturnCode of the IcingaError. + +.PARAMETER ClassName +| Name | Type | Description | Default | +|-----------|---------------|-----------------------------------------|---------| +| ClassName | System.String | Name of the CIM class to query. | | + +.PARAMETER Namespace +| Name | Type | Description | Default | +|-----------|---------------|--------------------------------|------------| +| Namespace | System.String | CIM namespace of the class. | root/cimv2 | + +.PARAMETER Filter +| Name | Type | Description | Default | +|--------|---------------|----------------------------------------------|---------| +| Filter | System.String | WQL filter, e.g. 'DriveType = 3'; '' for all. | | + +.PARAMETER Property +| Name | Type | Description | Default | +|----------|--------------|-------------------------------------------------|---------| +| Property | System.Array | Properties to fetch; empty fetches all of them. | @() | + +.OUTPUTS +System.Object[] — The CIM instances on success (an empty array when nothing +matches), or an IcingaError when the query failed. + +.EXAMPLE +PS> Get-IcingaWindowsInformation -ClassName 'Win32_Volume' -Filter 'DriveType = 3' -Property 'Name', 'Capacity', 'FreeSpace' + +Returns the local disk volumes with the three requested properties. + +.EXAMPLE +PS> $Mpio = Get-IcingaWindowsInformation -ClassName 'MPIO_DISK_INFO' -Namespace 'root/wmi' + +Returns an IcingaError with the return code WindowsInformationClassUnknown on +hosts without the MPIO feature. + +.NOTES +Windows-only, uses the local CIM provider. The required permissions depend on +the class; standard users can read most root/cimv2 classes. Unknown classes and +namespaces are logged at Debug level only, because optional classes are probed +on purpose. +#> +function Get-IcingaWindowsInformation() +{ + param ( + [string]$ClassName = '', + [string]$Namespace = 'root/cimv2', + [string]$Filter = '', + [array]$Property = @() + ); + + if ([string]::IsNullOrEmpty($ClassName)) { + return (Write-FunctionReturnValue -ReturnValue 'WindowsInformationClassNameMissing' -Data @{ 'Namespace' = $Namespace; } -OverrideReturn (('IcingaError' -as [type])::new('WindowsInformationClassNameMissing', 'No CIM class name was provided for the query', @{ 'Namespace' = $Namespace; }))); + } + + [hashtable]$QueryArguments = @{ + 'ClassName' = $ClassName; + 'Namespace' = $Namespace; + 'ErrorAction' = 'Stop'; + }; + + if ([string]::IsNullOrEmpty($Filter) -eq $false) { + $QueryArguments.Add('Filter', $Filter); + } + + if ($Property.Count -ne 0) { + $QueryArguments.Add('Property', [string[]]$Property); + } + + try { + [array]$Instances = @(Get-CimInstance @QueryArguments); + } catch { + [hashtable]$NativeErrorCodes = @{ + 'InvalidClass' = 'WindowsInformationClassUnknown'; + 'InvalidNamespace' = 'WindowsInformationNamespaceInvalid'; + 'AccessDenied' = 'WindowsInformationAccessDenied'; + 'InvalidQuery' = 'WindowsInformationInvalidQuery'; + 'NoSuchProperty' = 'WindowsInformationInvalidQuery'; + 'InvalidParameter' = 'WindowsInformationInvalidQuery'; + }; + + [string]$NativeErrorCode = [string]$_.Exception.NativeErrorCode; + [string]$ReturnCode = 'WindowsInformationQueryFailed'; + + if ($NativeErrorCodes.ContainsKey($NativeErrorCode)) { + $ReturnCode = $NativeErrorCodes[$NativeErrorCode]; + } + + [hashtable]$ErrorData = @{ + 'ClassName' = $ClassName; + 'Namespace' = $Namespace; + 'Filter' = $Filter; + 'Error' = $_.Exception.Message; + }; + + Set-InternalExitCodes; + + [string]$CodeMessage = (Get-GlobalRuntimeVariable).Public.ReturnCodes[$ReturnCode].Message; + [string]$ErrorMessage = [string]::Format('{0}: Class "{1}", Namespace "{2}": {3}', $CodeMessage, $ClassName, $Namespace, ([string]$_.Exception.Message).Trim()); + + return (Write-FunctionReturnValue -ReturnValue $ReturnCode -Data $ErrorData -OverrideReturn (('IcingaError' -as [type])::new($ReturnCode, $ErrorMessage, $ErrorData))); + } + + # The leading comma keeps the instances an array, even for one or no instance. + return ,(Write-FunctionReturnValue -ReturnValue 'WindowsInformationQueried' -Data @{ 'ClassName' = $ClassName; 'Namespace' = $Namespace; 'Count' = $Instances.Count; } -OverrideReturn $Instances); +} diff --git a/src/Tools/Public/Test-IcingaArrayFilter.ps1 b/src/Tools/Public/Test-IcingaArrayFilter.ps1 new file mode 100644 index 0000000..67a52c1 --- /dev/null +++ b/src/Tools/Public/Test-IcingaArrayFilter.ps1 @@ -0,0 +1,96 @@ +<# +.SYNOPSIS +Test a value against include and exclude wildcard lists + +.DESCRIPTION +Test-IcingaArrayFilter decides whether a value passes the usual plugin filters +-Include and -Exclude, without any script block. Both lists hold wildcard +patterns ('*', '?', '[a-z]') that are compared case-insensitively against the +value converted to a string. An exclude match always wins; with an empty include +list every value that is not excluded passes, otherwise at least one include +pattern has to match. + +A single value returns a boolean. An array returns a new array with every +element that passes, so a whole list can be filtered in one call. An invalid +wildcard pattern is logged through Write-FunctionReturnValue +(ArrayFilterInvalidPattern) and the value is treated as not matching that +pattern. + +.PARAMETER InputObject +| Name | Type | Description | Default | +|-------------|---------------|----------------------------------------------|---------| +| InputObject | System.Object | Value, or array of values, to test. | $null | + +.PARAMETER Include +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------------------|---------| +| Include | System.Array | Wildcard patterns of which at least one has to match. | @() | + +.PARAMETER Exclude +| Name | Type | Description | Default | +|---------|--------------|-----------------------------------------------|---------| +| Exclude | System.Array | Wildcard patterns of which none may match. | @() | + +.OUTPUTS +System.Boolean — For a single value, whether it passes the filters. +System.Object[] — For an array, the elements that pass the filters. + +.EXAMPLE +PS> Test-IcingaArrayFilter -InputObject 'Spooler' -Include 'Spo*' -Exclude 'WinRM' + +Returns $true. + +.EXAMPLE +PS> Test-IcingaArrayFilter -InputObject @('C', 'D', 'E') -Exclude 'D' + +Returns the array @('C', 'E'). + +.NOTES +No external dependencies. A $null value never passes. Used by the plugins for +their -Include/-Exclude parameters, which must not rely on script blocks so the +plugins stay usable in JEA sessions. +#> +function Test-IcingaArrayFilter() +{ + param ( + $InputObject = $null, + [array]$Include = @(), + [array]$Exclude = @() + ); + + if ($InputObject -is [array]) { + [array]$Filtered = @(); + + foreach ($Entry in $InputObject) { + if (Test-IcingaArrayFilter -InputObject $Entry -Include $Include -Exclude $Exclude) { + $Filtered += $Entry; + } + } + + return ,$Filtered; + } + + if ($null -eq $InputObject) { + return $false; + } + + [string]$Value = [string]$InputObject; + + foreach ($Pattern in $Exclude) { + if (Test-ModuleWildcardMatch -Value $Value -Pattern ([string]$Pattern)) { + return $false; + } + } + + if ($Include.Count -eq 0) { + return $true; + } + + foreach ($Pattern in $Include) { + if (Test-ModuleWildcardMatch -Value $Value -Pattern ([string]$Pattern)) { + return $true; + } + } + + return $false; +} From 72a53dc1054aabed1b92cba6c0b56becdbe91fbd Mon Sep 17 00:00:00 2001 From: Fabian Thomys Date: Fri, 2 Oct 2026 16:40:15 +0200 Subject: [PATCH 2/6] Add Process plugin --- Tests/Get-IcingaProcessInformation.Tests.ps1 | 191 ++++++++++++ Tests/Invoke-IcingaCheckProcess.Tests.ps1 | 152 ++++++++++ .../Private/Set-InternalExitCodes.ps1 | 12 + .../Public/Invoke-IcingaCheckProcess.ps1 | 279 ++++++++++++++++++ .../Public/Get-IcingaProcessInformation.ps1 | 194 ++++++++++++ 5 files changed, 828 insertions(+) create mode 100644 Tests/Get-IcingaProcessInformation.Tests.ps1 create mode 100644 Tests/Invoke-IcingaCheckProcess.Tests.ps1 create mode 100644 src/Plugins/Public/Invoke-IcingaCheckProcess.ps1 create mode 100644 src/Provider/Process/Public/Get-IcingaProcessInformation.ps1 diff --git a/Tests/Get-IcingaProcessInformation.Tests.ps1 b/Tests/Get-IcingaProcessInformation.Tests.ps1 new file mode 100644 index 0000000..7d03b28 --- /dev/null +++ b/Tests/Get-IcingaProcessInformation.Tests.ps1 @@ -0,0 +1,191 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Get-IcingaProcessInformation' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + # Builds the -StructureByInstance result of the process counters. Every + # process is @(instance, id, cpu, memory, pagefile, threads); a string id + # becomes the counter error of an instance that ended between the reads. + function New-TestProcessCounter() + { + param ( + [array]$Processes = @( + @('powershell', 100, 50, 104857600, 52428800, 10), + @('powershell#1', 200, 30, 209715200, 62914560, 20), + @('svchost', 300, 8, 10485760, 5242880, 5), + @('_Total', 0, 400, 1073741824, 1073741824, 900), + @('Idle', 0, 300, 8192, 0, 8), + @('gone', 'The instance "gone" does not exist in the category "Process"', 0, 0, 0, 0) + ) + ); + + [hashtable]$Result = @{ }; + + foreach ($Process in $Processes) { + [hashtable]$Values = @{ }; + [array]$Counters = @( + @('ID Process', $Process[1]), + @('% Processor Time', $Process[2]), + @('Working Set - Private', $Process[3]), + @('Page File Bytes', $Process[4]), + @('Thread Count', $Process[5]) + ); + + foreach ($Counter in $Counters) { + $Leaf = @{ 'value' = [decimal]0; 'sample' = $null; 'help' = ''; 'type' = ''; 'error' = $null; }; + + if ($Counter[1] -is [string]) { + $Leaf['error'] = $Counter[1]; + } else { + $Leaf['value'] = [decimal]$Counter[1]; + } + + $Values[$Counter[0]] = $Leaf; + } + + $Result[$Process[0]] = @{ 'Process' = $Values; }; + } + + return $Result; + } + + # Runs the provider inside the module scope with the CIM and performance counter + # functions shadowed. 16GiB installed memory, 4 logical processors, 20GiB commit limit. + function Invoke-TestProcessInformation() + { + param ( + $Counters = (New-TestProcessCounter), + $CommitLimit = [decimal]21474836480, + [hashtable]$Arguments = @{ }, + [string]$FailClass = '' + ); + + return (& $script:IcingaModule { + param ($Counters, $CommitLimit, $Arguments, $FailClass); + + function New-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @() + ); + } + + function Get-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @(), + [int]$TimeoutMs = 5000, + [switch]$StructureByInstance = $false + ); + + if ($StructureByInstance) { + return $Counters; + } + + $Leaf = @{ 'value' = [decimal]0; 'sample' = $null; 'help' = ''; 'type' = ''; 'error' = $null; }; + + if ($CommitLimit -is [string]) { + $Leaf['error'] = $CommitLimit; + } else { + $Leaf['value'] = [decimal]$CommitLimit; + } + + return @{ '\Memory\Commit Limit' = $Leaf; }; + } + + function Get-IcingaWindowsInformation() + { + param ( + [string]$ClassName = '', + [string]$Namespace = 'root/cimv2', + [string]$Filter = '', + [array]$Property = @() + ); + + if ($ClassName -eq $FailClass) { + return [IcingaError]::new('WindowsInformationAccessDenied', 'Simulated failure of ' + $ClassName, @{ }); + } + + return ,@([PSCustomObject]@{ 'TotalPhysicalMemory' = [uint64]17179869184; 'NumberOfLogicalProcessors' = [uint32]4; }); + } + + Get-IcingaProcessInformation @Arguments; + } $Counters $CommitLimit $Arguments $FailClass); + } + } + + It 'groups the processes by name and keys every process by its id' { + $Data = Invoke-TestProcessInformation; + + @($Data.Processes.Keys | Sort-Object) | Should -Be @('powershell', 'svchost'); + @($Data.Processes['powershell'].Instances.Keys | Sort-Object) | Should -Be @('100', '200'); + $Data.Processes['powershell'].Instances['200'].Memory | Should -Be 209715200; + $Data.Processes['powershell'].Instances['200'].PageFile | Should -Be 62914560; + $Data.Processes['powershell'].Instances['200'].Threads | Should -Be 20; + } + + It 'divides the CPU usage by the number of logical processors' { + $Data = Invoke-TestProcessInformation; + + $Data.Processes['powershell'].Instances['100'].Cpu | Should -Be 12.5; + $Data.Processes['powershell'].Instances['200'].Cpu | Should -Be 7.5; + $Data.Processes['svchost'].Instances['300'].Cpu | Should -Be 2; + $Data.LogicalProcessors | Should -Be 4; + } + + It 'sums every process of a name' { + $Total = (Invoke-TestProcessInformation).Processes['powershell'].Total; + + $Total.Cpu | Should -Be 20; + $Total.Memory | Should -Be 314572800; + $Total.PageFile | Should -Be 115343360; + $Total.Threads | Should -Be 30; + $Total.Count | Should -Be 2; + } + + It 'leaves out _Total, Idle and processes that ended between the reads' { + $Data = Invoke-TestProcessInformation; + + $Data.Processes.ContainsKey('_Total') | Should -BeFalse; + $Data.Processes.ContainsKey('Idle') | Should -BeFalse; + $Data.Processes.ContainsKey('gone') | Should -BeFalse; + } + + It 'returns the installed memory and the commit limit' { + $Data = Invoke-TestProcessInformation; + + $Data.MemoryTotal | Should -Be 17179869184; + $Data.CommitLimit | Should -Be 21474836480; + } + + It 'filters the processes by name' { + @((Invoke-TestProcessInformation -Arguments @{ 'Include' = @('power*'); }).Processes.Keys) | Should -Be @('powershell'); + @((Invoke-TestProcessInformation -Arguments @{ 'Exclude' = @('POWERSHELL'); }).Processes.Keys) | Should -Be @('svchost'); + } + + It 'returns the IcingaError of a failed CIM query' { + $Data = Invoke-TestProcessInformation -FailClass 'Win32_ComputerSystem'; + + (Test-IcingaError -InputObject $Data) | Should -BeTrue; + $Data.Message | Should -Be 'Simulated failure of Win32_ComputerSystem'; + } + + It 'returns an IcingaError when the counters cannot be read' { + $Data = Invoke-TestProcessInformation -Counters $null; + (Test-IcingaError -InputObject $Data) | Should -BeTrue; + $Data.ReturnCode | Should -Be 'ProcessCounterReadFailed'; + + $Data = Invoke-TestProcessInformation -Counters @{ }; + (Test-IcingaError -InputObject $Data) | Should -BeTrue; + + $Data = Invoke-TestProcessInformation -CommitLimit 'Counter not initialized'; + (Test-IcingaError -InputObject $Data) | Should -BeTrue; + $Data.Message | Should -Match 'Commit Limit'; + } +} diff --git a/Tests/Invoke-IcingaCheckProcess.Tests.ps1 b/Tests/Invoke-IcingaCheckProcess.Tests.ps1 new file mode 100644 index 0000000..83573e2 --- /dev/null +++ b/Tests/Invoke-IcingaCheckProcess.Tests.ps1 @@ -0,0 +1,152 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckProcess' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Two PowerShell processes on a host with 16GiB memory and a 4GiB commit limit. + function New-TestProcessData() + { + param ( + [uint64]$CommitLimit = 4294967296 + ); + + return @{ + 'MemoryTotal' = [uint64]17179869184; + 'CommitLimit' = $CommitLimit; + 'LogicalProcessors' = 4; + 'Processes' = @{ + 'powershell' = @{ + 'Name' = 'powershell'; + 'Instances' = @{ + '200' = @{ 'Id' = 200; 'Cpu' = [double]7.5; 'Memory' = [uint64]209715200; 'PageFile' = [uint64]62914560; 'Threads' = 20; }; + '100' = @{ 'Id' = 100; 'Cpu' = [double]12.5; 'Memory' = [uint64]104857600; 'PageFile' = [uint64]52428800; 'Threads' = 10; }; + }; + 'Total' = @{ 'Cpu' = [double]20; 'Memory' = [uint64]314572800; 'PageFile' = [uint64]115343360; 'Threads' = 30; 'Count' = 2; }; + }; + }; + }; + } + + # Runs the plugin inside the module scope with the provider shadowed. + function Invoke-TestProcessCheck() + { + param ( + $Data = (New-TestProcessData), + [hashtable]$Arguments = @{ } + ); + + return (& $script:IcingaModule { + param ($Data, $Arguments); + + function Get-IcingaProcessInformation() + { + param ( + [array]$Include = @(), + [array]$Exclude = @() + ); + + if ($Data -is [string]) { + return [IcingaError]::new('ProcessCounterReadFailed', $Data, @{ }); + } + + return $Data; + } + + Invoke-IcingaCheckProcess @Arguments; + } $Data $Arguments); + } + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'checks every process and the summary of every name' { + Invoke-TestProcessCheck -Arguments @{ 'Verbosity' = 2; } | Should -Be 0; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match ([regex]::Escape('[OK] Process Overview: 13 Ok')); + $Output | Should -Match ([regex]::Escape('\_ [OK] powershell [100]')); + $Output | Should -Match ([regex]::Escape('\_ [OK] CPU Usage: 12.5% is ok')); + $Output | Should -Match ([regex]::Escape('\_ [OK] Page File Usage: 50MiB is ok')); + $Output | Should -Match ([regex]::Escape('\_ [OK] powershell Summary')); + $Output | Should -Match ([regex]::Escape('\_ [OK] Process Count: 2 is ok')); + } + + It 'lists the single processes in the order of their ids' { + Invoke-TestProcessCheck -Arguments @{ 'Verbosity' = 2; } | Should -Be 0; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output.IndexOf('powershell [100]') | Should -BeLessThan $Output.IndexOf('powershell [200]'); + } + + It 'writes performance data for the summary only' { + Invoke-TestProcessCheck | Should -Be 0; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + 'powershell::ifw_process::pagefile=115343360B;;;0;4294967296', + 'powershell::ifw_process::memory=314572800B;;;0;17179869184', + 'powershell::ifw_process::cpu=20%;;;0;100', + 'powershell::ifw_process::threads=30;;;;', + 'powershell::ifw_process::count=2;;;;' + ); + } + + It 'applies the single thresholds to every process and the total thresholds to the summary' { + Invoke-TestProcessCheck -Arguments @{ 'CPUWarning' = '10'; 'TotalMemoryCritical' = '1%'; 'TotalProcessCountCritical' = '3:'; } | Should -Be 2; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match ([regex]::Escape('\_ [WARNING] powershell [100]')); + $Output | Should -Match ([regex]::Escape('[WARNING] CPU Usage: 12.5% is greater than threshold 10%')); + $Output | Should -Match ([regex]::Escape('[CRITICAL] Memory Usage: 300MiB (1.83%) is greater than threshold 163.84MiB (1%)')); + $Output | Should -Match ([regex]::Escape('[CRITICAL] Process Count: 2 is lower than threshold 3')); + $Output | Should -Not -Match ([regex]::Escape('powershell [200]')); + } + + It 'measures the page file usage against the commit limit' { + Invoke-TestProcessCheck -Arguments @{ 'TotalPageFileWarning' = '2%'; } | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[WARNING] Page File Usage: 110MiB (2.69%) is greater than threshold 81.92MiB (2%)')); + } + + It 'reports every requested process without a match with the OverrideNotFound state' { + Invoke-TestProcessCheck -Arguments @{ 'Process' = @('powershell', 'notepad', 'note*'); } | Should -Be 3; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match ([regex]::Escape('[UNKNOWN] notepad: Process not found')); + $Output | Should -Match ([regex]::Escape('[UNKNOWN] note*: Process not found')); + $Output | Should -Not -Match ([regex]::Escape('powershell: Process not found')); + + Invoke-TestProcessCheck -Arguments @{ 'Process' = @('notepad'); 'OverrideNotFound' = 'Critical'; } | Should -Be 2; + Invoke-TestProcessCheck -Arguments @{ 'Process' = @('notepad'); 'OverrideNotFound' = 'Ok'; } | Should -Be 0; + } + + It 'reports a provider error as UNKNOWN with its reason' { + Invoke-TestProcessCheck -Data 'Simulated counter failure' | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Process Overview: Simulated counter failure'; + } + + It 'reports UNKNOWN when no process matches' { + $Data = New-TestProcessData; + $Data['Processes'] = @{ }; + + Invoke-TestProcessCheck -Data $Data | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Process Overview: No process matches the given filter'; + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestProcessCheck -Arguments @{ 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } +} diff --git a/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 b/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 index b7d5203..b58098a 100644 --- a/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 +++ b/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 @@ -1192,6 +1192,18 @@ function Set-InternalExitCodes() 'Severity' = 'Debug'; 'Area' = 'Provider'; }; + 'ProcessCounterReadFailed' = @{ + 'Code' = 4500; + 'Message' = 'The performance counters for the process information could not be read'; + 'Severity' = 'Error'; + 'Area' = 'Provider'; + }; + 'ProcessInformationCollected' = @{ + 'Code' = 4550; + 'Message' = 'The process information was collected successfully'; + 'Severity' = 'Debug'; + 'Area' = 'Provider'; + }; 'WebUIAssetPathEmpty' = @{ 'Code' = 13000; 'Message' = 'No Web UI asset path was provided for retrieving the Web UI asset'; diff --git a/src/Plugins/Public/Invoke-IcingaCheckProcess.ps1 b/src/Plugins/Public/Invoke-IcingaCheckProcess.ps1 new file mode 100644 index 0000000..5c63012 --- /dev/null +++ b/src/Plugins/Public/Invoke-IcingaCheckProcess.ps1 @@ -0,0 +1,279 @@ +<# +.SYNOPSIS +Check the CPU, memory, page file and thread usage of processes against thresholds + +.DESCRIPTION +Reads every process once through Get-IcingaProcessInformation and builds a single +IcingaPlugin container named 'Process Overview'. Every process name becomes a +package with one package per process (' []') and a ' Summary' +package holding the sums of all processes with that name. Each of them checks the +page file usage, the memory usage (private working set), the CPU usage and the +thread count; the summary also checks the process count. + +The thresholds without 'Total' apply to every single process, the 'Total' +thresholds to the summary. Memory thresholds accept sizes ('500MB') and +percentages of the installed memory ('5%'). The page file usage is the commit +charge of the process; its percentages relate to the commit limit (installed +memory plus page files), because a commit charge can exceed the page file size. The CPU +usage is in percent of the whole machine (all logical processors), so '80' or +'80%' means 80 percent of the machine like in the task manager. All thresholds +accept the full Icinga range grammar. + +Process and ExcludeProcess select the processes by name without '.exe' +(wildcards allowed). Every entry of Process that matches no running process is +reported with the state chosen with OverrideNotFound (UNKNOWN by default). Without +Process every process is checked; for a plain process count of the whole system +this is more output than needed. + +Performance data is written for the summary only, with the labels +'::ifw_process::cpu', '::memory', '::pagefile', '::threads' and '::count'. + +.PARAMETER PageFileWarning +| Name | Type | Description | Default | +|-----------------|---------------|-----------------------------------------------------------------|---------| +| PageFileWarning | System.String | Warning threshold for the page file usage of each process. | | + +.PARAMETER PageFileCritical +| Name | Type | Description | Default | +|------------------|---------------|-----------------------------------------------------------------|---------| +| PageFileCritical | System.String | Critical threshold for the page file usage of each process. | | + +.PARAMETER MemoryWarning +| Name | Type | Description | Default | +|---------------|---------------|-------------------------------------------------------------|---------| +| MemoryWarning | System.String | Warning threshold for the memory usage of each process. | | + +.PARAMETER MemoryCritical +| Name | Type | Description | Default | +|----------------|---------------|-------------------------------------------------------------|---------| +| MemoryCritical | System.String | Critical threshold for the memory usage of each process. | | + +.PARAMETER CPUWarning +| Name | Type | Description | Default | +|------------|---------------|----------------------------------------------------------|---------| +| CPUWarning | System.String | Warning threshold for the CPU usage of each process. | | + +.PARAMETER CPUCritical +| Name | Type | Description | Default | +|-------------|---------------|----------------------------------------------------------|---------| +| CPUCritical | System.String | Critical threshold for the CPU usage of each process. | | + +.PARAMETER ThreadCountWarning +| Name | Type | Description | Default | +|--------------------|---------------|------------------------------------------------------------|---------| +| ThreadCountWarning | System.String | Warning threshold for the thread count of each process. | | + +.PARAMETER ThreadCountCritical +| Name | Type | Description | Default | +|---------------------|---------------|------------------------------------------------------------|---------| +| ThreadCountCritical | System.String | Critical threshold for the thread count of each process. | | + +.PARAMETER TotalPageFileWarning +| Name | Type | Description | Default | +|----------------------|---------------|--------------------------------------------------------------------|---------| +| TotalPageFileWarning | System.String | Warning threshold for the page file usage of all processes of a name. | | + +.PARAMETER TotalPageFileCritical +| Name | Type | Description | Default | +|-----------------------|---------------|--------------------------------------------------------------------|---------| +| TotalPageFileCritical | System.String | Critical threshold for the page file usage of all processes of a name. | | + +.PARAMETER TotalMemoryWarning +| Name | Type | Description | Default | +|--------------------|---------------|-----------------------------------------------------------------|---------| +| TotalMemoryWarning | System.String | Warning threshold for the memory usage of all processes of a name. | | + +.PARAMETER TotalMemoryCritical +| Name | Type | Description | Default | +|---------------------|---------------|-----------------------------------------------------------------|---------| +| TotalMemoryCritical | System.String | Critical threshold for the memory usage of all processes of a name. | | + +.PARAMETER TotalCPUWarning +| Name | Type | Description | Default | +|-----------------|---------------|--------------------------------------------------------------|---------| +| TotalCPUWarning | System.String | Warning threshold for the CPU usage of all processes of a name. | | + +.PARAMETER TotalCPUCritical +| Name | Type | Description | Default | +|------------------|---------------|--------------------------------------------------------------|---------| +| TotalCPUCritical | System.String | Critical threshold for the CPU usage of all processes of a name. | | + +.PARAMETER TotalThreadCountWarning +| Name | Type | Description | Default | +|-------------------------|---------------|----------------------------------------------------------------|---------| +| TotalThreadCountWarning | System.String | Warning threshold for the thread count of all processes of a name. | | + +.PARAMETER TotalThreadCountCritical +| Name | Type | Description | Default | +|--------------------------|---------------|----------------------------------------------------------------|---------| +| TotalThreadCountCritical | System.String | Critical threshold for the thread count of all processes of a name. | | + +.PARAMETER TotalProcessCountWarning +| Name | Type | Description | Default | +|--------------------------|---------------|----------------------------------------------------------|---------| +| TotalProcessCountWarning | System.String | Warning threshold for the number of processes of a name. | | + +.PARAMETER TotalProcessCountCritical +| Name | Type | Description | Default | +|---------------------------|---------------|-----------------------------------------------------------|---------| +| TotalProcessCountCritical | System.String | Critical threshold for the number of processes of a name. | | + +.PARAMETER Process +| Name | Type | Description | Default | +|---------|--------------|-----------------------------------------------------------------------|---------| +| Process | System.Array | Process names without '.exe' to check, wildcards allowed. Empty checks all. | @() | + +.PARAMETER ExcludeProcess +| Name | Type | Description | Default | +|----------------|--------------|----------------------------------------------------------|---------| +| ExcludeProcess | System.Array | Process names to skip, wildcards allowed. | @() | + +.PARAMETER OverrideNotFound +| Name | Type | Description | Default | +|------------------|---------------|------------------------------------------------------------------------|---------| +| OverrideNotFound | System.String | State for a Process entry without a match: Ok, Warning, Critical or Unknown. | Unknown | + +.PARAMETER Verbosity +| Name | Type | Description | Default | +|-----------|--------------|-----------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | + +.PARAMETER NoPerfData +| Name | Type | Description | Default | +|------------|----------------------------------------------|---------------------------------------|---------| +| NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | + +.OUTPUTS +System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). + +.EXAMPLE +PS> Invoke-IcingaCheckProcess -Process 'powershell' -Verbosity 2 + +Lists every PowerShell process and the summary of all of them. + +.EXAMPLE +PS> Invoke-IcingaCheckProcess -Process 'sqlservr' -CPUWarning '80' -TotalMemoryCritical '90%' -TotalProcessCountCritical '1:' + +Warns when one SQL Server process uses more than 80 percent of the machine, and +goes critical when all of them use more than 90 percent of the memory or none runs. + +.NOTES +Windows-only. Reads the '\Process(*)' performance counters ('Performance Monitor +Users'), '\Memory\Commit Limit' and the Win32_ComputerSystem CIM class through +Get-IcingaProcessInformation. The integer exit code is the return value; an Icinga +command wrapper is expected to exit with it. +#> +function Invoke-IcingaCheckProcess() +{ + param ( + [string]$PageFileWarning = '', + [string]$PageFileCritical = '', + [string]$MemoryWarning = '', + [string]$MemoryCritical = '', + [string]$CPUWarning = '', + [string]$CPUCritical = '', + [string]$ThreadCountWarning = '', + [string]$ThreadCountCritical = '', + [string]$TotalPageFileWarning = '', + [string]$TotalPageFileCritical = '', + [string]$TotalMemoryWarning = '', + [string]$TotalMemoryCritical = '', + [string]$TotalCPUWarning = '', + [string]$TotalCPUCritical = '', + [string]$TotalThreadCountWarning = '', + [string]$TotalThreadCountCritical = '', + [string]$TotalProcessCountWarning = '', + [string]$TotalProcessCountCritical = '', + [array]$Process = @(), + [array]$ExcludeProcess = @(), + [ValidateSet('Ok', 'Warning', 'Critical', 'Unknown')] + [string]$OverrideNotFound = 'Unknown', + [int]$Verbosity = 0, + [switch]$NoPerfData = $false + ); + + $CheckPackage = New-IcingaPlugin 'Process Overview'; + $CheckPackage.Verbose = $Verbosity; + + $Data = Get-IcingaProcessInformation -Include $Process -Exclude $ExcludeProcess; + + if (Test-IcingaError -InputObject $Data) { + return $CheckPackage.SetError($Data).Compile(); + } + + foreach ($Name in (ConvertTo-IcingaSortedArray -InputObject @($Data.Processes.Keys))) { + $Entry = $Data.Processes[$Name]; + $ProcessPackage = New-IcingaPlugin $Name; + [array]$Packages = @(); + + # Every package with its metrics: name, value, unit, base value, warning, + # critical and perfdata label. Single processes write no performance data. + foreach ($Id in (ConvertTo-IcingaSortedArray -InputObject @($Entry.Instances.Keys))) { + $Instance = $Entry.Instances[$Id]; + $Packages += ,@( + (New-IcingaPlugin ([string]::Format('{0} [{1}]', $Name, $Id))), + @( + @('Page File Usage', $Instance.PageFile, 'B', $Data.CommitLimit, $PageFileWarning, $PageFileCritical, ''), + @('Memory Usage', $Instance.Memory, 'B', $Data.MemoryTotal, $MemoryWarning, $MemoryCritical, ''), + @('CPU Usage', $Instance.Cpu, '%', 100, $CPUWarning, $CPUCritical, ''), + @('Thread Count', $Instance.Threads, '', 0, $ThreadCountWarning, $ThreadCountCritical, '') + ) + ); + } + + $Total = $Entry.Total; + $Packages += ,@( + (New-IcingaPlugin ([string]::Format('{0} Summary', $Name))), + @( + @('Page File Usage', $Total.PageFile, 'B', $Data.CommitLimit, $TotalPageFileWarning, $TotalPageFileCritical, 'pagefile'), + @('Memory Usage', $Total.Memory, 'B', $Data.MemoryTotal, $TotalMemoryWarning, $TotalMemoryCritical, 'memory'), + @('CPU Usage', $Total.Cpu, '%', 100, $TotalCPUWarning, $TotalCPUCritical, 'cpu'), + @('Thread Count', $Total.Threads, '', 0, $TotalThreadCountWarning, $TotalThreadCountCritical, 'threads'), + @('Process Count', $Total.Count, '', 0, $TotalProcessCountWarning, $TotalProcessCountCritical, 'count') + ) + ); + + foreach ($Package in $Packages) { + foreach ($Metric in $Package[1]) { + $Check = New-IcingaPlugin $Metric[0] $Metric[1] $Metric[2]; + $Check.NoPerfData = ($NoPerfData -or [string]::IsNullOrEmpty($Metric[6])); + + # Counts have no size to calculate percentages from. + if ([double]$Metric[3] -gt 0) { + $Check.BaseValue($Metric[3]).Minimum('0').Maximum([string]$Metric[3]).Commit(); + } + + # Perfdata label: ::ifw_process:: (template auto-derived from the command). + $Package[0].AddCheck( + $Check. + MetricIndex($Name). + MetricLabel($Metric[6]). + Warning($Metric[4]). + Critical($Metric[5]). + CheckRange() + ).Commit(); + } + + $ProcessPackage.AddCheck($Package[0]).Commit(); + } + + $CheckPackage.AddCheck($ProcessPackage).Commit(); + } + + [hashtable]$NotFoundStates = @{ + 'Ok' = 0; + 'Warning' = 1; + 'Critical' = 2; + 'Unknown' = 3; + }; + + # Wildcard entries are reported as well: a pattern without any match means the + # expected process is not running. + $CheckPackage.AddMissingChecks($Process, @($Data.Processes.Keys), '{0}', 'Process not found', $NotFoundStates[$OverrideNotFound]).Commit(); + + if ($CheckPackage.HasChecks() -eq $false) { + return $CheckPackage.SetError('No process matches the given filter').Compile(); + } + + return $CheckPackage.Compile(); +} diff --git a/src/Provider/Process/Public/Get-IcingaProcessInformation.ps1 b/src/Provider/Process/Public/Get-IcingaProcessInformation.ps1 new file mode 100644 index 0000000..3f66447 --- /dev/null +++ b/src/Provider/Process/Public/Get-IcingaProcessInformation.ps1 @@ -0,0 +1,194 @@ +<# +.SYNOPSIS +Collect the CPU, memory, page file and thread usage of every running process + +.DESCRIPTION +Get-IcingaProcessInformation is the data source of the process plugins. It reads +the counters 'ID Process', '% Processor Time', 'Working Set - Private', +'Page File Bytes' and 'Thread Count' of every process in one request from the +'\Process(*)' performance counter category, which the performance-counter daemon +keeps warm through a single category snapshot. The installed memory and the number +of logical processors come from Win32_ComputerSystem, the commit limit from the +'\Memory\Commit Limit' counter. + +The page file usage of a process is its commit charge ('Page File Bytes'): the +private memory the system guarantees to back with the page files. It can exceed the +size of the page files, so it is measured against the commit limit (installed +memory plus page files), which no commit charge can exceed. + +Processes are grouped by name. Windows names the counter instances of several +processes with the same name 'name', 'name#1', 'name#2' and so on; the suffix is +removed and every process is keyed by its process id. The '_Total' and 'Idle' +instances (process id 0) are left out. Include and Exclude filter the process +names (wildcards allowed, without '.exe'). + +The CPU usage of the counter is relative to one logical processor and is divided +by the number of logical processors, so 100 means the whole machine like in the +task manager. Win32_ComputerSystem is used for that number because +[Environment]::ProcessorCount only covers one processor group on Windows +PowerShell 5.1. + +.PARAMETER Include +| Name | Type | Description | Default | +|---------|--------------|----------------------------------------------------------|---------| +| Include | System.Array | Only collect processes matching these names (wildcards). | @() | + +.PARAMETER Exclude +| Name | Type | Description | Default | +|---------|--------------|-----------------------------------------------------|---------| +| Exclude | System.Array | Skip processes matching these names (wildcards). | @() | + +.OUTPUTS +System.Collections.Hashtable — Keys Processes, MemoryTotal, CommitLimit and +LogicalProcessors, or an IcingaError when the data could not be read. Processes is +keyed by process name; every entry holds Name, Instances (keyed by process id, each +with Id, Cpu, Memory, PageFile and Threads) and Total (Cpu, Memory, PageFile, +Threads and Count). Cpu is in percent of the machine, Memory (private working set), +PageFile and the totals are in bytes. + +.EXAMPLE +PS> (Get-IcingaProcessInformation -Include 'powershell').Processes['powershell'].Total + +Returns the summed usage of all PowerShell processes. + +.NOTES +Windows-only. Reads the '\Process(*)' performance counters ('Performance Monitor +Users'), '\Memory\Commit Limit' and the Win32_ComputerSystem CIM class. Without a +running daemon the first call in a runspace waits for the counter warm-up. +#> +function Get-IcingaProcessInformation() +{ + param ( + [array]$Include = @(), + [array]$Exclude = @() + ); + + # Literal declaration, so the counter discovery at module start finds and warms them. + New-IcingaPerformanceCounter -Counter @('\Process(*)\ID Process', '\Process(*)\% Processor Time', '\Process(*)\Working Set - Private', '\Process(*)\Page File Bytes', '\Process(*)\Thread Count', '\Memory\Commit Limit'); + + $ComputerSystem = Get-IcingaWindowsInformation -ClassName 'Win32_ComputerSystem' -Property 'TotalPhysicalMemory', 'NumberOfLogicalProcessors'; + + if (Test-IcingaError -InputObject $ComputerSystem) { + return $ComputerSystem; + } + + $Counters = Get-IcingaPerformanceCounter -Counter @('\Process(*)\ID Process', '\Process(*)\% Processor Time', '\Process(*)\Working Set - Private', '\Process(*)\Page File Bytes', '\Process(*)\Thread Count') -StructureByInstance; + + if ($null -eq $Counters -or $Counters.Count -eq 0) { + [hashtable]$ErrorData = @{ 'Counter' = '\Process(*)'; }; + return (Write-FunctionReturnValue -ReturnValue 'ProcessCounterReadFailed' -Data $ErrorData -OverrideReturn (('IcingaError' -as [type])::new('ProcessCounterReadFailed', 'The performance counters of the category Process could not be read', $ErrorData))); + } + + # Read on its own, so a process named like the category cannot collide with it in + # the structured result. + $Memory = Get-IcingaPerformanceCounter -Counter '\Memory\Commit Limit'; + $CommitLimit = $null; + + if ($null -ne $Memory) { + $CommitLimit = Get-IcingaPerformanceCounterValue -InputObject $Memory['\Memory\Commit Limit']; + } + + if ($null -eq $CommitLimit -or $CommitLimit -is [string]) { + [hashtable]$ErrorData = @{ 'Counter' = '\Memory\Commit Limit'; 'Error' = [string]$CommitLimit; }; + return (Write-FunctionReturnValue -ReturnValue 'ProcessCounterReadFailed' -Data $ErrorData -OverrideReturn (('IcingaError' -as [type])::new('ProcessCounterReadFailed', 'The performance counter \Memory\Commit Limit could not be read', $ErrorData))); + } + + [double]$Processors = [System.Math]::Max([double]1, [double]$ComputerSystem[0].NumberOfLogicalProcessors); + [hashtable]$Processes = @{ }; + + foreach ($InstanceName in $Counters.Keys) { + $Values = $Counters[$InstanceName]['Process']; + + if ($null -eq $Values) { + continue; + } + + # An instance that ended between the snapshots has no readable id. + $Id = Get-IcingaPerformanceCounterValue -InputObject $Values['ID Process']; + + if ($null -eq $Id -or $Id -is [string] -or [int]$Id -eq 0) { + continue; + } + + # Windows replaces a '#' in a process name, so only the duplicate suffix uses it. + [string]$Name = $InstanceName; + [int]$Suffix = $Name.LastIndexOf('#'); + + if ($Suffix -gt 0) { + $Name = $Name.Substring(0, $Suffix); + } + + if ((Test-IcingaArrayFilter -InputObject $Name -Include $Include -Exclude $Exclude) -eq $false) { + continue; + } + + [double]$Cpu = 0; + [uint64]$Memory = 0; + [uint64]$PageFile = 0; + [int]$Threads = 0; + + $Value = Get-IcingaPerformanceCounterValue -InputObject $Values['% Processor Time']; + if ($null -ne $Value -and $Value -isnot [string]) { + $Cpu = [double]$Value / $Processors; + } + + $Value = Get-IcingaPerformanceCounterValue -InputObject $Values['Working Set - Private']; + if ($null -ne $Value -and $Value -isnot [string]) { + $Memory = [uint64]$Value; + } + + $Value = Get-IcingaPerformanceCounterValue -InputObject $Values['Page File Bytes']; + if ($null -ne $Value -and $Value -isnot [string]) { + $PageFile = [uint64]$Value; + } + + $Value = Get-IcingaPerformanceCounterValue -InputObject $Values['Thread Count']; + if ($null -ne $Value -and $Value -isnot [string]) { + $Threads = [int]$Value; + } + + if ($Processes.ContainsKey($Name) -eq $false) { + $Processes[$Name] = @{ + 'Name' = $Name; + 'Instances' = @{ }; + 'Total' = @{ + 'Cpu' = [double]0; + 'Memory' = [uint64]0; + 'PageFile' = [uint64]0; + 'Threads' = 0; + 'Count' = 0; + }; + }; + } + + $Entry = $Processes[$Name]; + + $Entry['Instances'][[string][int]$Id] = @{ + 'Id' = [int]$Id; + 'Cpu' = [System.Math]::Round($Cpu, 2); + 'Memory' = $Memory; + 'PageFile' = $PageFile; + 'Threads' = $Threads; + }; + + $Entry['Total']['Cpu'] += $Cpu; + $Entry['Total']['Memory'] += $Memory; + $Entry['Total']['PageFile'] += $PageFile; + $Entry['Total']['Threads'] += $Threads; + $Entry['Total']['Count'] += 1; + } + + # The totals are summed unrounded and rounded once, so they match the processes. + foreach ($Entry in $Processes.Values) { + $Entry['Total']['Cpu'] = [System.Math]::Round([double]$Entry['Total']['Cpu'], 2); + } + + [hashtable]$Result = @{ + 'Processes' = $Processes; + 'MemoryTotal' = [uint64]$ComputerSystem[0].TotalPhysicalMemory; + 'CommitLimit' = [uint64]$CommitLimit; + 'LogicalProcessors' = [int]$Processors; + }; + + return (Write-FunctionReturnValue -ReturnValue 'ProcessInformationCollected' -Data @{ 'Count' = $Processes.Count; } -OverrideReturn $Result); +} From 14765027cc3c0713cc37fc232920f4e423843011 Mon Sep 17 00:00:00 2001 From: Lord Hepipud Date: Wed, 11 Nov 2026 18:54:54 +0100 Subject: [PATCH 3/6] Add ScheduledTask plugin and refactor plugins to use IcingaPlugin comfort methods - Add Invoke-IcingaCheckScheduledTask plugin, Get-IcingaScheduledTask provider, IcingaScheduledTaskStatus lookup class and unit tests - Add ScheduledTaskQueryFailed internal exit code (2500) in Set-InternalExitCodes - Enhance Test-IcingaArrayFilter to accept a single value or an array via -Value - Refactor all 9 check plugins (CPU, Directory, Memory, PartitionSpace, PerfCounter, Process, ScheduledTask, Service, Uptime) to use IcingaPlugin comfort features (.SetHidden(), .SetNoPerfData(), .SetState(), .SetNotice(), .Translate(), .AddMissingChecks() with string states, and root-level NoPerfData inheritance) - Update Directory and Uptime unit tests for notice summary exclusions and enforce code styling across all branch files --- Tests/ConvertTo-IcingaSortedArray.Tests.ps1 | 6 +- .../Get-IcingaDirectoryInformation.Tests.ps1 | 30 +- Tests/Get-IcingaScheduledTask.Tests.ps1 | 121 ++++++++ Tests/Get-IcingaWindowsInformation.Tests.ps1 | 2 +- Tests/IcingaScheduledTaskStatus.Tests.ps1 | 90 ++++++ Tests/Invoke-IcingaCheckCPU.Tests.ps1 | 4 +- Tests/Invoke-IcingaCheckDirectory.Tests.ps1 | 12 +- Tests/Invoke-IcingaCheckMemory.Tests.ps1 | 6 +- ...Invoke-IcingaCheckPartitionSpace.Tests.ps1 | 2 +- Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 | 12 +- Tests/Invoke-IcingaCheckProcess.Tests.ps1 | 4 +- .../Invoke-IcingaCheckScheduledTask.Tests.ps1 | 178 ++++++++++++ Tests/Invoke-IcingaCheckService.Tests.ps1 | 4 +- Tests/Invoke-IcingaCheckUptime.Tests.ps1 | 6 +- Tests/Test-IcingaArrayFilter.Tests.ps1 | 2 +- .../DataTypes/IcingaScheduledTaskStatus.ps1 | 99 +++++++ .../DataTypes/IcingaServiceStartupType.ps1 | 12 +- src/Classes/DataTypes/IcingaServiceStatus.ps1 | 12 +- src/Classes/Tools/IcingaSortKey.ps1 | 22 +- .../Private/Set-InternalExitCodes.ps1 | 74 +---- src/Plugins/Public/Invoke-IcingaCheckCPU.ps1 | 44 ++- .../Public/Invoke-IcingaCheckDirectory.ps1 | 162 +++++------ .../Public/Invoke-IcingaCheckMemory.ps1 | 34 +-- .../Invoke-IcingaCheckPartitionSpace.ps1 | 46 ++- .../Public/Invoke-IcingaCheckPerfCounter.ps1 | 59 ++-- .../Public/Invoke-IcingaCheckProcess.ps1 | 107 ++++--- .../Invoke-IcingaCheckScheduledTask.ps1 | 275 ++++++++++++++++++ .../Public/Invoke-IcingaCheckService.ps1 | 118 +++----- .../Public/Invoke-IcingaCheckUptime.ps1 | 35 +-- .../Disk/Public/Get-IcingaDiskInformation.ps1 | 6 +- .../Public/Get-IcingaDirectoryInformation.ps1 | 106 +++---- .../Public/Get-IcingaProcessInformation.ps1 | 4 +- .../Public/Get-IcingaScheduledTask.ps1 | 188 ++++++++++++ .../Private/Test-ModuleWildcardMatch.ps1 | 2 +- .../Public/ConvertTo-IcingaSortedArray.ps1 | 14 +- .../Public/Get-IcingaWindowsInformation.ps1 | 12 +- src/Tools/Public/Test-IcingaArrayFilter.ps1 | 10 +- 37 files changed, 1376 insertions(+), 544 deletions(-) create mode 100644 Tests/Get-IcingaScheduledTask.Tests.ps1 create mode 100644 Tests/IcingaScheduledTaskStatus.Tests.ps1 create mode 100644 Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 create mode 100644 src/Classes/DataTypes/IcingaScheduledTaskStatus.ps1 create mode 100644 src/Plugins/Public/Invoke-IcingaCheckScheduledTask.ps1 create mode 100644 src/Provider/ScheduledTask/Public/Get-IcingaScheduledTask.ps1 diff --git a/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 b/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 index ed69f99..383908f 100644 --- a/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 +++ b/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 @@ -31,7 +31,7 @@ Describe 'ConvertTo-IcingaSortedArray' { $Objects = @([PSCustomObject]@{ 'Name' = 'Spooler'; }, [PSCustomObject]@{ 'Name' = 'AppInfo'; }); (ConvertTo-IcingaSortedArray -InputObject $Objects -Property 'Name').Name | Should -Be @('AppInfo', 'Spooler'); - $Tables = @(@{ 'Name' = 'D:\'; }, @{ 'Name' = 'C:\'; }); + $Tables = @(@{ 'Name' = 'D:\'; }, @{ 'Name' = 'C:\'; }); (ConvertTo-IcingaSortedArray -InputObject $Tables -Property 'Name') | ForEach-Object { $_['Name'] } | Should -Be @('C:\', 'D:\'); } @@ -41,7 +41,7 @@ Describe 'ConvertTo-IcingaSortedArray' { @{ 'Disk' = 0; 'Partition' = 2; }, @{ 'Disk' = 0; 'Partition' = 1; } ); - $Sorted = ConvertTo-IcingaSortedArray -InputObject $Partitions -Property 'Disk', 'Partition'; + $Sorted = ConvertTo-IcingaSortedArray -InputObject $Partitions -Property 'Disk', 'Partition'; ($Sorted | ForEach-Object { '{0}:{1}' -f $_['Disk'], $_['Partition'] }) | Should -Be @('0:1', '0:2', '1:1'); } @@ -70,7 +70,7 @@ Describe 'ConvertTo-IcingaSortedArray' { ($Single -is [array]) | Should -BeTrue; $Single.Count | Should -Be 1; - $Empty = ConvertTo-IcingaSortedArray -InputObject @(); + $Empty = ConvertTo-IcingaSortedArray -InputObject @(); ($Empty -is [array]) | Should -BeTrue; $Empty.Count | Should -Be 0; } diff --git a/Tests/Get-IcingaDirectoryInformation.Tests.ps1 b/Tests/Get-IcingaDirectoryInformation.Tests.ps1 index da838ed..ccdf7de 100644 --- a/Tests/Get-IcingaDirectoryInformation.Tests.ps1 +++ b/Tests/Get-IcingaDirectoryInformation.Tests.ps1 @@ -13,12 +13,12 @@ Describe 'Get-IcingaDirectoryInformation' { function New-TestFile() { param ( - [string]$Path = '', - [int]$Size = 0, - [datetime]$LastWrite = [datetime]::Now, - [datetime]$Creation = [datetime]::Now, - [datetime]$LastAccess = [datetime]::Now, - [switch]$Hidden = $false + [string]$Path = '', + [int]$Size = 0, + [datetime]$LastWrite = [datetime]::Now, + [datetime]$Creation = [datetime]::Now, + [datetime]$LastAccess = [datetime]::Now, + [switch]$Hidden = $false ); [System.IO.File]::WriteAllBytes($Path, [byte[]]::new($Size)); @@ -50,11 +50,11 @@ Describe 'Get-IcingaDirectoryInformation' { # created 40d ago, last access 40d ago), hidden.log 10 (hidden), # sub\ (written 3d ago) with d.log 5000 (2d) and deep\e.log 1 (now), # hidden\ (hidden folder) with f.log 7. - [datetime]$Now = [datetime]::Now; - $script:Root = Join-Path -Path $TestDrive -ChildPath 'scan'; - [string]$Sub = Join-Path -Path $script:Root -ChildPath 'sub'; - [string]$Deep = Join-Path -Path $Sub -ChildPath 'deep'; - [string]$Secret = Join-Path -Path $script:Root -ChildPath 'hidden'; + [datetime]$Now = [datetime]::Now; + $script:Root = Join-Path -Path $TestDrive -ChildPath 'scan'; + [string]$Sub = Join-Path -Path $script:Root -ChildPath 'sub'; + [string]$Deep = Join-Path -Path $Sub -ChildPath 'deep'; + [string]$Secret = Join-Path -Path $script:Root -ChildPath 'hidden'; New-Item -Path $Deep -ItemType Directory -Force | Out-Null; New-Item -Path $Secret -ItemType Directory -Force | Out-Null; @@ -146,7 +146,7 @@ Describe 'Get-IcingaDirectoryInformation' { } It 'returns the kept entries with IncludeFileList' { - $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'IncludeFileList' = $true; }; + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'IncludeFileList' = $true; }; [array]$Names = @($Result.FileList | ForEach-Object { $_.Name } | Sort-Object); $Names | Should -Be @('a.log', 'b.log', 'c.txt', 'sub'); @@ -180,7 +180,7 @@ Describe 'Get-IcingaDirectoryInformation' { It 'reports a missing path, or an empty result with IgnoreMissingPath' { [string]$Missing = Join-Path -Path $TestDrive -ChildPath 'missing'; - $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $Missing; }; + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $Missing; }; $Result.ReturnCode | Should -Be 'DirectoryPathNotFound'; $Result.Message | Should -Be ([string]::Format('The directory "{0}" does not exist on this system', $Missing)); @@ -195,12 +195,12 @@ Describe 'Get-IcingaDirectoryInformation' { [string]$Locked = Join-Path -Path $TestDrive -ChildPath 'locked'; New-Item -Path $Locked -ItemType Directory -Force | Out-Null; - $Rule = New-Object System.Security.AccessControl.FileSystemAccessRule( + $Rule = New-Object System.Security.AccessControl.FileSystemAccessRule( [System.Security.Principal.WindowsIdentity]::GetCurrent().Name, [System.Security.AccessControl.FileSystemRights]::ListDirectory, [System.Security.AccessControl.AccessControlType]::Deny ); - $Acl = Get-Acl -Path $Locked; + $Acl = Get-Acl -Path $Locked; $Acl.AddAccessRule($Rule); Set-Acl -Path $Locked -AclObject $Acl; diff --git a/Tests/Get-IcingaScheduledTask.Tests.ps1 b/Tests/Get-IcingaScheduledTask.Tests.ps1 new file mode 100644 index 0000000..4dbc3c5 --- /dev/null +++ b/Tests/Get-IcingaScheduledTask.Tests.ps1 @@ -0,0 +1,121 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +function Invoke-TestGetScheduledTask() +{ + param ( + [array]$Tasks = @(), + [hashtable]$Infos = @{ }, + [hashtable]$Arguments = @{ }, + [switch]$Fail = $false + ); + + return (& $script:IcingaModule { + param ($Tasks, $Infos, $Arguments, $Fail); + + function Get-ScheduledTask() + { + param ( + [string]$TaskName = '*', + [string]$ErrorAction = 'Continue' + ); + + if ($Fail) { + throw 'Access is denied'; + } + + return $Tasks; + } + + function Get-ScheduledTaskInfo() + { + param ( + [string]$TaskName = '', + [string]$TaskPath = '', + [string]$ErrorAction = 'Continue' + ); + + [string]$Key = '{0}{1}' -f $TaskPath, $TaskName; + if ($Infos.ContainsKey($Key)) { + return $Infos[$Key]; + } + + return $null; + } + + return (Get-IcingaScheduledTask @Arguments); + } $Tasks $Infos $Arguments $Fail); +} + +Describe 'Get-IcingaScheduledTask' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + } + + Context 'Task collection and filtering' { + It 'groups tasks by TaskPath and resolves runtime info' { + [datetime]$Past = [datetime]::Now.AddHours(-2); + [datetime]$Future = [datetime]::Now.AddHours(1); + + $Tasks = @( + [PSCustomObject]@{ 'TaskName' = 'Renew Certificate'; 'TaskPath' = '\Icinga\'; 'State' = 'Ready' }, + [PSCustomObject]@{ 'TaskName' = 'Backup'; 'TaskPath' = '\Microsoft\'; 'State' = 'Disabled' } + ); + $Infos = @{ + '\Icinga\Renew Certificate' = [PSCustomObject]@{ + 'LastRunTime' = $Past; + 'NextRunTime' = $Future; + 'NumberOfMissedRuns' = 1; + 'LastTaskResult' = 0; + }; + '\Microsoft\Backup' = [PSCustomObject]@{ + 'LastRunTime' = [datetime]::new(1999, 11, 30, 0, 0, 0); + 'NextRunTime' = $null; + 'NumberOfMissedRuns' = 0; + 'LastTaskResult' = 267011; + }; + }; + + $Result = Invoke-TestGetScheduledTask -Tasks $Tasks -Infos $Infos; + $Result.Tasks.Count | Should -Be 2; + $Result.Tasks['\Icinga\'][0].TaskName | Should -Be 'Renew Certificate'; + [string]$Result.Tasks['\Icinga\'][0].State | Should -Be 'Ready'; + $Result.Tasks['\Icinga\'][0].MissedRuns | Should -Be 1; + $Result.Tasks['\Icinga\'][0].LastRunOffset | Should -BeGreaterThan 7000; + $Result.Tasks['\Icinga\'][0].NextRunOffset | Should -BeGreaterThan 3000; + + # 1999-11-30 with 267011 (SCHED_S_TASK_HAS_NOT_RUN) is treated as never run. + $Result.Tasks['\Microsoft\'][0].LastRunTime | Should -Be ''; + $Result.Tasks['\Microsoft\'][0].LastRunOffset | Should -Be 0; + $Result.Tasks['\Microsoft\'][0].NextRunTime | Should -Be ''; + $Result.Tasks['\Microsoft\'][0].NextRunOffset | Should -Be 0; + } + + It 'filters by TaskName, ExcludeTaskName, TaskPath and ExcludeTaskPath' { + $Tasks = @( + [PSCustomObject]@{ 'TaskName' = 'TaskA'; 'TaskPath' = '\Icinga\'; 'State' = 'Ready' }, + [PSCustomObject]@{ 'TaskName' = 'TaskB'; 'TaskPath' = '\Icinga\'; 'State' = 'Ready' }, + [PSCustomObject]@{ 'TaskName' = 'TaskC'; 'TaskPath' = '\Other\'; 'State' = 'Ready' } + ); + + $Result = Invoke-TestGetScheduledTask -Tasks $Tasks -Arguments @{ + 'TaskPath' = '\Icinga\*'; + 'ExcludeTaskName' = 'TaskB'; + }; + + $Result.Tasks.Count | Should -Be 1; + $Result.Tasks['\Icinga\'].Count | Should -Be 1; + $Result.Tasks['\Icinga\'][0].TaskName | Should -Be 'TaskA'; + $Result.TaskNames | Should -Be @('TaskA'); + } + + It 'returns an IcingaError when Get-ScheduledTask fails' { + $Result = Invoke-TestGetScheduledTask -Fail; + (Test-IcingaError -InputObject $Result) | Should -BeTrue; + } + } +} diff --git a/Tests/Get-IcingaWindowsInformation.Tests.ps1 b/Tests/Get-IcingaWindowsInformation.Tests.ps1 index f34c8f8..c6d9919 100644 --- a/Tests/Get-IcingaWindowsInformation.Tests.ps1 +++ b/Tests/Get-IcingaWindowsInformation.Tests.ps1 @@ -92,7 +92,7 @@ Describe 'Get-IcingaWindowsInformation' { $Plain.Value[0].Bound | Should -Not -Contain 'Filter'; $Plain.Value[0].Bound | Should -Not -Contain 'Property'; - $Full = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'MSFT_Disk'; 'Namespace' = 'root/Microsoft/Windows/Storage'; 'Filter' = 'Number = 0'; 'Property' = @('Number', 'Size'); } -EchoArguments; + $Full = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'MSFT_Disk'; 'Namespace' = 'root/Microsoft/Windows/Storage'; 'Filter' = 'Number = 0'; 'Property' = @('Number', 'Size'); } -EchoArguments; $Full.Value[0].Namespace | Should -Be 'root/Microsoft/Windows/Storage'; $Full.Value[0].Filter | Should -Be 'Number = 0'; $Full.Value[0].Property | Should -Be @('Number', 'Size'); diff --git a/Tests/IcingaScheduledTaskStatus.Tests.ps1 b/Tests/IcingaScheduledTaskStatus.Tests.ps1 new file mode 100644 index 0000000..ac0b29a --- /dev/null +++ b/Tests/IcingaScheduledTaskStatus.Tests.ps1 @@ -0,0 +1,90 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'IcingaScheduledTaskStatus' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + } + + Context 'Enum values' { + It 'keeps the Task Scheduler state codes used by the state perfdata' { + $Codes = & $script:IcingaModule { + return @( + [int][IcingaScheduledTaskStatus]::Unknown, + [int][IcingaScheduledTaskStatus]::Disabled, + [int][IcingaScheduledTaskStatus]::Queued, + [int][IcingaScheduledTaskStatus]::Ready, + [int][IcingaScheduledTaskStatus]::Running + ); + }; + $Codes | Should -Be @(0, 1, 2, 3, 4); + } + + It 'converts names in any casing and codes as a parameter type' { + $Converted = & $script:IcingaModule { + function Test-IcingaScheduledTaskStatusParameter() + { + param ( + [IcingaScheduledTaskStatus]$State = 'Ready' + ); + + return [string]$State; + } + + return @( + (Test-IcingaScheduledTaskStatusParameter), + (Test-IcingaScheduledTaskStatusParameter -State 'disabled'), + (Test-IcingaScheduledTaskStatusParameter -State 4) + ); + }; + $Converted | Should -Be @('Ready', 'Disabled', 'Running'); + } + + It 'rejects an unknown name as a parameter value' { + { + & $script:IcingaModule { + function Test-IcingaScheduledTaskStatusParameter() + { + param ( + [IcingaScheduledTaskStatus]$State = 'Ready' + ); + + return $State; + } + + Test-IcingaScheduledTaskStatusParameter -State 'Sleeping'; + }; + } | Should -Throw; + } + } + + Context 'IcingaScheduledTaskStatusMap' { + It 'resolves names in any casing and numeric codes' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaScheduledTaskStatusMap]::Resolve('Ready'), + [string][IcingaScheduledTaskStatusMap]::Resolve('running'), + [string][IcingaScheduledTaskStatusMap]::Resolve(1), + [string][IcingaScheduledTaskStatusMap]::Resolve('2') + ); + }; + $Resolved | Should -Be @('Ready', 'Running', 'Disabled', 'Queued'); + } + + It 'resolves unmappable values to Unknown' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaScheduledTaskStatusMap]::Resolve($null), + [string][IcingaScheduledTaskStatusMap]::Resolve(''), + [string][IcingaScheduledTaskStatusMap]::Resolve('InvalidState'), + [string][IcingaScheduledTaskStatusMap]::Resolve(99) + ); + }; + $Resolved | Should -Be @('Unknown', 'Unknown', 'Unknown', 'Unknown'); + } + } +} diff --git a/Tests/Invoke-IcingaCheckCPU.Tests.ps1 b/Tests/Invoke-IcingaCheckCPU.Tests.ps1 index a133fc5..b031e5e 100644 --- a/Tests/Invoke-IcingaCheckCPU.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckCPU.Tests.ps1 @@ -5,7 +5,7 @@ if (-not (Get-Module -Name 'IcingaForWindows')) { Describe 'Invoke-IcingaCheckCPU' { BeforeAll { - $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; @@ -118,7 +118,7 @@ Describe 'Invoke-IcingaCheckCPU' { } It 'reports the same node total and overall load on a single NUMA node' { - $Counters = New-TestCpuCounter -Instances @{ '0,0' = 13.18; '0,1' = 9.67; '0,2' = 6.52; '0,3' = 1.13; '0,_Total' = 7.44; '_Total' = 7.57; }; + $Counters = New-TestCpuCounter -Instances @{ '0,0' = 13.18; '0,1' = 9.67; '0,2' = 6.52; '0,3' = 1.13; '0,_Total' = 7.44; '_Total' = 7.57; }; Invoke-TestCpuCheck -StubData $Counters | Should -Be 0; diff --git a/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 b/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 index 14b5fa6..b9e4808 100644 --- a/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 @@ -5,7 +5,7 @@ if (-not (Get-Module -Name 'IcingaForWindows')) { Describe 'Invoke-IcingaCheckDirectory' { BeforeAll { - $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; @@ -119,7 +119,7 @@ Describe 'Invoke-IcingaCheckDirectory' { Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'Verbosity' = 2; } | Should -Be 0; [array]$Lines = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n"; - $Lines[0] | Should -Be '[OK] Directory Check: "C:\Backup": 7 Ok'; + $Lines[0] | Should -Be '[OK] Directory Check: "C:\Backup": 6 Ok'; $Lines[1] | Should -Be '\_ [OK] File Count: 3 is ok'; $Lines[3] | Should -Be '\_ [OK] Total Size: 6KiB is ok'; $Lines[6] | Should -Be '\_ [OK] Average File Size: 2KiB is ok'; @@ -130,7 +130,7 @@ Describe 'Invoke-IcingaCheckDirectory' { Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'Critical' = '2'; 'WarningTotalSize' = '5KiB'; } | Should -Be 2; $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; - $Output | Should -Match ([regex]::Escape('[CRITICAL] Directory Check: "C:\Backup": 1 Critical 1 Warning 5 Ok')); + $Output | Should -Match ([regex]::Escape('[CRITICAL] Directory Check: "C:\Backup": 1 Critical 1 Warning 4 Ok')); $Output | Should -Match ([regex]::Escape('[CRITICAL] File Count: 3 is greater than threshold 2')); $Output | Should -Match ([regex]::Escape('[WARNING] Total Size: 6KiB is greater than threshold 5KiB')); } @@ -181,19 +181,19 @@ Describe 'Invoke-IcingaCheckDirectory' { [System.IO.File]::WriteAllBytes((Join-Path -Path $ListRoot -ChildPath 'b.bak'), [byte[]]::new(2048)); [System.IO.File]::WriteAllBytes((Join-Path -Path $ListRoot -ChildPath 'a.bak'), [byte[]]::new(1024)); - [array]$Entries = @( + [array]$Entries = @( [System.IO.FileInfo]::new((Join-Path -Path $ListRoot -ChildPath 'b.bak')), [System.IO.DirectoryInfo]::new((Join-Path -Path $ListRoot -ChildPath 'folder')), [System.IO.FileInfo]::new((Join-Path -Path $ListRoot -ChildPath 'a.bak')) ); - $Data = New-TestDirectoryData -FileCount 2 -FolderCount 1 -TotalSize 3072 -SmallestFile 1024 -LargestFile 2048 -FileList $Entries; + $Data = New-TestDirectoryData -FileCount 2 -FolderCount 1 -TotalSize 3072 -SmallestFile 1024 -LargestFile 2048 -FileList $Entries; Invoke-TestDirectoryCheck -StubData $Data -Arguments @{ 'Path' = 'C:\Backup'; 'ShowFileList' = $true; } | Should -Be 0; $Global:IcingaTestDirectoryCall['IncludeFileList'] | Should -BeTrue; [array]$Lines = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n"; - $Lines[0] | Should -Be '[OK] Directory Check: "C:\Backup": 7 Ok'; + $Lines[0] | Should -Be '[OK] Directory Check: "C:\Backup": 6 Ok'; $Lines[8] | Should -Be '\_ [INFO] File List'; $Lines[9] | Should -Be ([string]::Format(' \_ [INFO] {0}: 1KiB', (Join-Path -Path $ListRoot -ChildPath 'a.bak'))); $Lines[10] | Should -Be ([string]::Format(' \_ [INFO] {0}: 2KiB', (Join-Path -Path $ListRoot -ChildPath 'b.bak'))); diff --git a/Tests/Invoke-IcingaCheckMemory.Tests.ps1 b/Tests/Invoke-IcingaCheckMemory.Tests.ps1 index c046059..1f27e8c 100644 --- a/Tests/Invoke-IcingaCheckMemory.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckMemory.Tests.ps1 @@ -5,7 +5,7 @@ if (-not (Get-Module -Name 'IcingaForWindows')) { Describe 'Invoke-IcingaCheckMemory' { BeforeAll { - $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; @@ -46,8 +46,8 @@ Describe 'Invoke-IcingaCheckMemory' { ); return @{ - 'Win32_ComputerSystem' = @([PSCustomObject]@{ 'TotalPhysicalMemory' = [uint64]17179869184; 'AutomaticManagedPagefile' = $AutomaticManagedPagefile; }); - 'Win32_PageFileUsage' = @( + 'Win32_ComputerSystem' = @([PSCustomObject]@{ 'TotalPhysicalMemory' = [uint64]17179869184; 'AutomaticManagedPagefile' = $AutomaticManagedPagefile; }); + 'Win32_PageFileUsage' = @( [PSCustomObject]@{ 'Name' = 'D:\pagefile.sys'; 'AllocatedBaseSize' = [uint32]1024; 'CurrentUsage' = [uint32]1000; }, [PSCustomObject]@{ 'Name' = 'C:\pagefile.sys'; 'AllocatedBaseSize' = [uint32]2048; 'CurrentUsage' = [uint32]512; } ); diff --git a/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 b/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 index c1a4159..4721a55 100644 --- a/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 @@ -5,7 +5,7 @@ if (-not (Get-Module -Name 'IcingaForWindows')) { Describe 'Invoke-IcingaCheckPartitionSpace' { BeforeAll { - $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; diff --git a/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 b/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 index e870f03..b120105 100644 --- a/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 @@ -5,7 +5,7 @@ if (-not (Get-Module -Name 'IcingaForWindows')) { Describe 'Invoke-IcingaCheckPerfCounter' { BeforeAll { - $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; @@ -64,10 +64,10 @@ Describe 'Invoke-IcingaCheckPerfCounter' { '\Processor(0)\% Processor Time' = (New-TestLeaf -Value 10 -Type 'Timer100NsInverse'); '\Processor(_Total)\% Processor Time' = (New-TestLeaf -Value 52.5 -Type 'Timer100NsInverse'); }; - '\Memory\Available Bytes' = (New-TestLeaf -Value 50 -Type 'NumberOfItems64'); - '\Nope\Nothing' = (New-TestLeaf -Value "Category 'Nope' does not exist."); - '\Disk(*)\Reads' = @{ }; - '\Broken(*)\Value' = @{ + '\Memory\Available Bytes' = (New-TestLeaf -Value 50 -Type 'NumberOfItems64'); + '\Nope\Nothing' = (New-TestLeaf -Value "Category 'Nope' does not exist."); + '\Disk(*)\Reads' = @{ }; + '\Broken(*)\Value' = @{ '\Broken(a)\Value' = (New-TestLeaf -Value 'Counter not initialized'); '\Broken(b)\Value' = (New-TestLeaf -Value 'Instance vanished'); }; @@ -167,7 +167,7 @@ Describe 'Invoke-IcingaCheckPerfCounter' { } It 'reports an empty result as UNKNOWN, or OK with IgnoreEmptyChecks' { - [hashtable]$Arguments = @{ 'PerfCounter' = @('\Processor(*)\% Processor Time'); 'IncludeCounter' = @('*(9)*'); }; + [hashtable]$Arguments = @{ 'PerfCounter' = @('\Processor(*)\% Processor Time'); 'IncludeCounter' = @('*(9)*'); }; Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments $Arguments | Should -Be 3; $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Performance Counter: No performance counter matches the given filter'; diff --git a/Tests/Invoke-IcingaCheckProcess.Tests.ps1 b/Tests/Invoke-IcingaCheckProcess.Tests.ps1 index 83573e2..3e331f5 100644 --- a/Tests/Invoke-IcingaCheckProcess.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckProcess.Tests.ps1 @@ -5,7 +5,7 @@ if (-not (Get-Module -Name 'IcingaForWindows')) { Describe 'Invoke-IcingaCheckProcess' { BeforeAll { - $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; @@ -138,7 +138,7 @@ Describe 'Invoke-IcingaCheckProcess' { } It 'reports UNKNOWN when no process matches' { - $Data = New-TestProcessData; + $Data = New-TestProcessData; $Data['Processes'] = @{ }; Invoke-TestProcessCheck -Data $Data | Should -Be 3; diff --git a/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 b/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 new file mode 100644 index 0000000..8314fee --- /dev/null +++ b/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 @@ -0,0 +1,178 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +function Invoke-TestScheduledTaskCheck() +{ + param ( + [array]$Tasks = @(), + [hashtable]$Infos = @{ }, + [hashtable]$Arguments = @{ }, + [switch]$Fail = $false + ); + + return (& $script:IcingaModule { + param ($Tasks, $Infos, $Arguments, $Fail); + + function Get-ScheduledTask() + { + param ( + [string]$TaskName = '*', + [string]$ErrorAction = 'Continue' + ); + + if ($Fail) { + throw 'Access is denied'; + } + + return $Tasks; + } + + function Get-ScheduledTaskInfo() + { + param ( + [string]$TaskName = '', + [string]$TaskPath = '', + [string]$ErrorAction = 'Continue' + ); + + [string]$Key = '{0}{1}' -f $TaskPath, $TaskName; + if ($Infos.ContainsKey($Key)) { + return $Infos[$Key]; + } + + return $null; + } + + return (Invoke-IcingaCheckScheduledTask @Arguments); + } $Tasks $Infos $Arguments $Fail); +} + +Describe 'Invoke-IcingaCheckScheduledTask' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + $script:DefaultTask = [PSCustomObject]@{ + 'TaskName' = 'Renew Certificate'; + 'TaskPath' = '\Icinga\Icinga for Windows\'; + 'State' = 'Ready'; + }; + $script:DefaultInfo = @{ + '\Icinga\Icinga for Windows\Renew Certificate' = [PSCustomObject]@{ + 'LastRunTime' = [datetime]::Now.AddHours(-1); + 'NextRunTime' = [datetime]::Now.AddHours(2); + 'NumberOfMissedRuns' = 0; + 'LastTaskResult' = 0; + }; + }; + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + Context 'State checks and multi-value State arrays' { + It 'returns OK when task state matches a single or multi-value State list and emits perfdata' { + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'State' = @('Ready', 'Running'); 'Verbosity' = 2; } | Should -Be 0; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape("[OK] State: 'Ready' is ok")); + $Result.PerformanceData | Should -Contain 'icinga_icingaforwindows_renewcertificate::ifw_scheduledtask::state=3;;;;'; + $Result.PerformanceData | Should -Contain 'icinga_icingaforwindows_renewcertificate::ifw_scheduledtask::missedruns=0;;;;'; + $Result.PerformanceData | Should -Contain 'icinga_icingaforwindows_renewcertificate::ifw_scheduledtask::lasttaskresult=0;;;;'; + } + + It 'returns CRITICAL when task state does not match the required State list' { + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'State' = @('Disabled'); 'Verbosity' = 2; } | Should -Be 2; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape("[CRITICAL] State: 'Ready' does not equal pattern 'Disabled'")); + } + } + + Context 'Exit codes, Missed Runs and Run Time thresholds' { + It 'raises CRITICAL on a non-zero LastTaskResult unless ignored via IgnoreLastRunTime or IgnoreExitCodes' { + $FailedInfo = @{ + '\Icinga\Icinga for Windows\Renew Certificate' = [PSCustomObject]@{ + 'LastRunTime' = [datetime]::Now.AddHours(-1); + 'NextRunTime' = $null; + 'NumberOfMissedRuns' = 0; + 'LastTaskResult' = 267009; + }; + }; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $FailedInfo | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match 'Task exited with code 267009'; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $FailedInfo -Arguments @{ 'IgnoreLastRunTime' = $true; } | Should -Be 0; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $FailedInfo -Arguments @{ 'IgnoreExitCodes' = @('0x41301'); } | Should -Be 0; + } + + It 'evaluates WarningMissedRuns and WarningLastRunTime thresholds' { + $Info = @{ + '\Icinga\Icinga for Windows\Renew Certificate' = [PSCustomObject]@{ + 'LastRunTime' = [datetime]::Now.AddHours(-5); + 'NextRunTime' = $null; + 'NumberOfMissedRuns' = 3; + 'LastTaskResult' = 0; + }; + }; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $Info -Arguments @{ 'WarningMissedRuns' = '2'; } | Should -Be 1; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $Info -Arguments @{ 'CriticalLastRunTime' = '2h'; } | Should -Be 2; + } + + It 'renders unset run times as [Never]: Never with 0s perfdata' { + $NeverInfo = @{ + '\Icinga\Icinga for Windows\Renew Certificate' = [PSCustomObject]@{ + 'LastRunTime' = $null; + 'NextRunTime' = $null; + 'NumberOfMissedRuns' = 0; + 'LastTaskResult' = 0; + }; + }; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $NeverInfo -Arguments @{ 'Verbosity' = 3; } | Should -Be 0; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('[INFO] Last Run Time [Never]: Never')); + $Result.Output | Should -Match ([regex]::Escape('[INFO] Next Run Time [Never]: Never')); + $Result.PerformanceData | Should -Contain 'icinga_icingaforwindows_renewcertificate::ifw_scheduledtask::lastruntime=0s;;;;'; + $Result.PerformanceData | Should -Contain 'icinga_icingaforwindows_renewcertificate::ifw_scheduledtask::nextruntime=0s;;;;'; + } + } + + Context 'Missing tasks and empty filter handling' { + It 'reports a missing required task with OverrideNotFound (UNKNOWN by default)' { + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'TaskName' = @('Renew Certificate', 'MissingTask'); } | Should -Be 3; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[UNKNOWN] MissingTask: Task not found')); + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'TaskName' = @('MissingTask'); 'OverrideNotFound' = 'Critical'; } | Should -Be 2; + } + + It 'returns UNKNOWN when no task matches a wildcard filter, or OK with MitigateUnknown' { + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'TaskPath' = '\DoesNotExist\*'; } | Should -Be 3; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Scheduled Tasks: No scheduled task matches the given filter'; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'TaskPath' = '\DoesNotExist\*'; 'MitigateUnknown' = $true; } | Should -Be 0; + } + + It 'returns UNKNOWN when querying scheduled tasks fails' { + Invoke-TestScheduledTaskCheck -Fail | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match '^\[UNKNOWN\] Scheduled Tasks: Failed to query scheduled tasks: Access is denied'; + } + } +} diff --git a/Tests/Invoke-IcingaCheckService.Tests.ps1 b/Tests/Invoke-IcingaCheckService.Tests.ps1 index b53b89e..28c50fc 100644 --- a/Tests/Invoke-IcingaCheckService.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckService.Tests.ps1 @@ -5,7 +5,7 @@ if (-not (Get-Module -Name 'IcingaForWindows')) { Describe 'Invoke-IcingaCheckService' { BeforeAll { - $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; @@ -188,7 +188,7 @@ Describe 'Invoke-IcingaCheckService' { Invoke-TestServiceCheck -StubData $Services | Should -Be 2; - $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; $Result.Output | Should -Match '^\[CRITICAL\] Services: 1 Critical 2 Ok'; $Result.Output | Should -Match ([regex]::Escape('Service "Auto Failed (AutoFailed)"')); $Result.Output | Should -Not -Match 'ManualStopped'; diff --git a/Tests/Invoke-IcingaCheckUptime.Tests.ps1 b/Tests/Invoke-IcingaCheckUptime.Tests.ps1 index 9dae030..77e465f 100644 --- a/Tests/Invoke-IcingaCheckUptime.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckUptime.Tests.ps1 @@ -5,7 +5,7 @@ if (-not (Get-Module -Name 'IcingaForWindows')) { Describe 'Invoke-IcingaCheckUptime' { BeforeAll { - $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; @@ -76,9 +76,9 @@ Describe 'Invoke-IcingaCheckUptime' { It 'shows the uptime as duration and writes it in whole seconds' { Invoke-TestUptimeCheck -StubData (New-TestUptimeCounter -Value 93784.4) -Arguments @{ 'Warning' = '1d:'; 'Verbosity' = 2; } | Should -Be 0; - $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; [array]$Lines = $Result.Output -split "`n"; - $Lines[0] | Should -Be '[OK] System Uptime: 1d 2h 3m 4s: 2 Ok'; + $Lines[0] | Should -Be '[OK] System Uptime: 1d 2h 3m 4s: 1 Ok'; $Lines[1] | Should -Be '\_ [OK] System Uptime: 1d 2h 3m 4s is ok'; $Lines[2] | Should -Match '^\\_ \[INFO\] Last Boot: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$'; $Result.PerformanceData | Should -Be @('windows::ifw_uptime::uptime=93784s;86400:;;;'); diff --git a/Tests/Test-IcingaArrayFilter.Tests.ps1 b/Tests/Test-IcingaArrayFilter.Tests.ps1 index dfe76f0..8e9ed6a 100644 --- a/Tests/Test-IcingaArrayFilter.Tests.ps1 +++ b/Tests/Test-IcingaArrayFilter.Tests.ps1 @@ -50,7 +50,7 @@ Describe 'Test-IcingaArrayFilter' { ($Single -is [array]) | Should -BeTrue; $Single.Count | Should -Be 1; - $None = Test-IcingaArrayFilter -InputObject @('C', 'D') -Include 'Q'; + $None = Test-IcingaArrayFilter -InputObject @('C', 'D') -Include 'Q'; ($None -is [array]) | Should -BeTrue; $None.Count | Should -Be 0; } diff --git a/src/Classes/DataTypes/IcingaScheduledTaskStatus.ps1 b/src/Classes/DataTypes/IcingaScheduledTaskStatus.ps1 new file mode 100644 index 0000000..703e256 --- /dev/null +++ b/src/Classes/DataTypes/IcingaScheduledTaskStatus.ps1 @@ -0,0 +1,99 @@ +<# +.SYNOPSIS +Status of a Windows scheduled task with its numeric status code + +.DESCRIPTION +IcingaScheduledTaskStatus lists every state a Windows scheduled task can be in. +The numeric values (0 Unknown, 1 Disabled, 2 Queued, 3 Ready, 4 Running) match +the Windows Task Scheduler StateEnum and are written as the task state +performance data. + +The enum is used directly as a parameter type, so a plugin parameter such as +[IcingaScheduledTaskStatus[]]$State accepts 'Ready', 'Running' or 3 and rejects +invalid values with the list of valid names. A value converts to its numeric +code with [int] and to its display name with [string]. + +.OUTPUTS +IcingaScheduledTaskStatus -- Enum value of the scheduled task status. + +.EXAMPLE +PS> [int][IcingaScheduledTaskStatus]::Ready + +Returns 3, the code used for the scheduled task state performance data. + +.NOTES +Defined in the kernel ahead of every function, so functions may use it as a +parameter type. Not visible outside the module scope; callers pass the name or +code as a string. +#> +enum IcingaScheduledTaskStatus +{ + Unknown = 0; + Disabled = 1; + Queued = 2; + Ready = 3; + Running = 4; +} + +<# +.SYNOPSIS +Map external scheduled task status values onto IcingaScheduledTaskStatus + +.DESCRIPTION +IcingaScheduledTaskStatusMap converts the status representations returned by +Get-ScheduledTask (CimInstance StateEnum, strings or numeric codes) into an +IcingaScheduledTaskStatus. Any value that cannot be mapped resolves to Unknown +instead of throwing, so a plugin can always report a state. + +.OUTPUTS +IcingaScheduledTaskStatusMap -- Static helper class, not meant to be instantiated. + +.EXAMPLE +PS> [IcingaScheduledTaskStatusMap]::Resolve('Ready') + +Returns IcingaScheduledTaskStatus::Ready. + +.NOTES +Pure conversion helper without state or external dependencies. +#> +class IcingaScheduledTaskStatusMap +{ + <# + .SYNOPSIS + Resolve a scheduled task status value into an IcingaScheduledTaskStatus + + .DESCRIPTION + Removes blanks from the value and converts it into an + IcingaScheduledTaskStatus by name (case-insensitive) or by numeric code. + Returns Unknown for $null, empty strings, unknown names and undefined codes. + + .PARAMETER Value + | Name | Type | Description | Default | + |-------|---------------|-----------------------------------------------------------|---------| + | Value | System.Object | Status name, ScheduledTask StateEnum or numeric code. | | + + .OUTPUTS + IcingaScheduledTaskStatus -- The resolved status, Unknown when it cannot be mapped. + + .EXAMPLE + PS> [IcingaScheduledTaskStatusMap]::Resolve('Running') + + .NOTES + PowerShell enum conversion rejects undefined codes, so '-as' returns $null for + them and they fall back to Unknown like unknown names. + #> + static [IcingaScheduledTaskStatus] Resolve([object]$Value) + { + if ($null -eq $Value) { + return [IcingaScheduledTaskStatus]::Unknown; + } + + $Status = ([string]$Value).Replace(' ', '') -as [IcingaScheduledTaskStatus]; + + if ($null -eq $Status) { + return [IcingaScheduledTaskStatus]::Unknown; + } + + return $Status; + } +} diff --git a/src/Classes/DataTypes/IcingaServiceStartupType.ps1 b/src/Classes/DataTypes/IcingaServiceStartupType.ps1 index 96405a9..3fc7832 100644 --- a/src/Classes/DataTypes/IcingaServiceStartupType.ps1 +++ b/src/Classes/DataTypes/IcingaServiceStartupType.ps1 @@ -13,7 +13,7 @@ The enum is used directly as a parameter type, so a plugin parameter such as 3 and rejects anything else with the list of valid names. .OUTPUTS -IcingaServiceStartupType — Enum value of the service startup type. +IcingaServiceStartupType -- Enum value of the service startup type. .EXAMPLE PS> [IcingaServiceStartupType]'Manual' @@ -48,7 +48,7 @@ codes. Every value that cannot be mapped resolves to Unknown instead of throwing. .OUTPUTS -IcingaServiceStartupTypeMap — Static helper class, not meant to be instantiated. +IcingaServiceStartupTypeMap -- Static helper class, not meant to be instantiated. .EXAMPLE PS> [IcingaServiceStartupTypeMap]::Resolve('Auto') @@ -70,12 +70,12 @@ class IcingaServiceStartupTypeMap Returns Unknown for $null, empty, unknown names and undefined codes. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|--------------------------------------------------------------|---------| - | Value | System.Object | Startup type name, Win32_Service start mode, ServiceStartMode or code. | | + | Name | Type | Description | Default | + |-------|---------------|------------------------------------------------------------------------|---------| + | Value | System.Object | Startup type name, Win32_Service start mode, ServiceStartMode or code. | | .OUTPUTS - IcingaServiceStartupType — The resolved startup type, Unknown when it cannot be mapped. + IcingaServiceStartupType -- The resolved startup type, Unknown when it cannot be mapped. .EXAMPLE PS> [IcingaServiceStartupTypeMap]::Resolve('Disabled') diff --git a/src/Classes/DataTypes/IcingaServiceStatus.ps1 b/src/Classes/DataTypes/IcingaServiceStatus.ps1 index 8687fd1..b1855b9 100644 --- a/src/Classes/DataTypes/IcingaServiceStatus.ps1 +++ b/src/Classes/DataTypes/IcingaServiceStatus.ps1 @@ -15,7 +15,7 @@ anything else with the list of valid names. A value converts to its code with [int] and to its name with [string]. .OUTPUTS -IcingaServiceStatus — Enum value of the service status. +IcingaServiceStatus -- Enum value of the service status. .EXAMPLE PS> [int][IcingaServiceStatus]::Running @@ -52,7 +52,7 @@ cannot be mapped resolves to Unknown instead of throwing, so a plugin can always report a state. .OUTPUTS -IcingaServiceStatusMap — Static helper class, not meant to be instantiated. +IcingaServiceStatusMap -- Static helper class, not meant to be instantiated. .EXAMPLE PS> [IcingaServiceStatusMap]::Resolve('Start Pending') @@ -74,12 +74,12 @@ class IcingaServiceStatusMap unknown names and undefined codes. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|----------------------------------------------------------------|---------| - | Value | System.Object | Status name, Win32_Service state, ServiceControllerStatus or code. | | + | Name | Type | Description | Default | + |-------|---------------|---------------------------------------------------------------------|---------| + | Value | System.Object | Status name, Win32_Service state, ServiceControllerStatus or code. | | .OUTPUTS - IcingaServiceStatus — The resolved status, Unknown when it cannot be mapped. + IcingaServiceStatus -- The resolved status, Unknown when it cannot be mapped. .EXAMPLE PS> [IcingaServiceStatusMap]::Resolve('Running') diff --git a/src/Classes/Tools/IcingaSortKey.ps1 b/src/Classes/Tools/IcingaSortKey.ps1 index 160896d..4141989 100644 --- a/src/Classes/Tools/IcingaSortKey.ps1 +++ b/src/Classes/Tools/IcingaSortKey.ps1 @@ -18,7 +18,7 @@ and sorts first. Several properties are joined with a separator that sorts below every other character, so the next property only breaks ties of the previous one. .OUTPUTS -IcingaSortKey — Static helper class, not meant to be instantiated. +IcingaSortKey -- Static helper class, not meant to be instantiated. .EXAMPLE PS> [IcingaSortKey]::FromObject($Volume, [string[]]@('Name')) @@ -43,17 +43,17 @@ class IcingaSortKey by key, every other object (including CIM instances) by member name. .PARAMETER InputObject - | Name | Type | Description | Default | - |-------------|---------------|---------------------------|---------| - | InputObject | System.Object | The object to build for. | | + | Name | Type | Description | Default | + |-------------|---------------|--------------------------|---------| + | InputObject | System.Object | The object to build for. | | .PARAMETER Property - | Name | Type | Description | Default | - |----------|-----------------|---------------------------------------------------|---------| - | Property | System.String[] | Properties in order of precedence; empty uses the object. | | + | Name | Type | Description | Default | + |----------|-----------------|----------------------------------------------------------|---------| + | Property | System.String[] | Properties in order of precedence; empty uses the object.| | .OUTPUTS - System.String — The sort key. + System.String -- The sort key. .EXAMPLE PS> [IcingaSortKey]::FromObject($Partition, [string[]]@('DiskNumber', 'PartitionNumber')) @@ -90,7 +90,7 @@ class IcingaSortKey | Value | System.Object | The value to build for. | | .OUTPUTS - System.String — The sort key. + System.String -- The sort key. .EXAMPLE PS> [IcingaSortKey]::FromValue('0,10') @@ -118,7 +118,7 @@ class IcingaSortKey if ([char]::IsDigit($Chunk[0])) { [string]$Digits = $Chunk.TrimStart('0'); - $Key += $Digits.Length.ToString('000') + $Digits; + $Key = $Key + $Digits.Length.ToString('000') + $Digits; } else { $Key += $Chunk; } @@ -146,7 +146,7 @@ class IcingaSortKey | Name | System.String | Key or member name. | | .OUTPUTS - System.Object — The property value or $null. + System.Object -- The property value or $null. .EXAMPLE PS> [IcingaSortKey]::GetMemberValue($Volume, 'Name') diff --git a/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 b/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 index b58098a..9e3aba5 100644 --- a/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 +++ b/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 @@ -10,7 +10,7 @@ longer description, severity and area metadata. The function is idempotent and will return immediately if the table is already set. .OUTPUTS -None — Populates (Get-GlobalRuntimeVariable).Public.ReturnCodes as a side effect. +None -- Populates (Get-GlobalRuntimeVariable).Public.ReturnCodes as a side effect. .EXAMPLE PS> Set-InternalExitCodes @@ -1132,75 +1132,15 @@ function Set-InternalExitCodes() 'Severity' = 'Warning'; 'Area' = 'Tools'; }; - 'DiskInformationVolumeQueryFailed' = @{ - 'Code' = 4300; - 'Message' = 'The volume data for the disk information could not be read'; + 'ScheduledTaskQueryFailed' = @{ + 'Code' = 4600; + 'Message' = 'The scheduled tasks could not be queried'; 'Severity' = 'Error'; 'Area' = 'Provider'; }; - 'DiskInformationPartitionQueryFailed' = @{ - 'Code' = 4301; - 'Message' = 'The partition data for the disk information could not be read'; - 'Severity' = 'Error'; - 'Area' = 'Provider'; - }; - 'DiskInformationDiskQueryFailed' = @{ - 'Code' = 4302; - 'Message' = 'The physical disk data for the disk information could not be read'; - 'Severity' = 'Error'; - 'Area' = 'Provider'; - }; - 'DiskInformationCollected' = @{ - 'Code' = 4350; - 'Message' = 'The disk information was collected successfully'; - 'Severity' = 'Debug'; - 'Area' = 'Provider'; - }; - 'DirectoryPathMissing' = @{ - 'Code' = 4400; - 'Message' = 'No directory path was provided'; - 'Severity' = 'Error'; - 'Area' = 'Provider'; - }; - 'DirectoryPathNotFound' = @{ - 'Code' = 4401; - 'Message' = 'The directory does not exist on this system'; - 'Severity' = 'Error'; - 'Area' = 'Provider'; - }; - 'DirectoryAccessDenied' = @{ - 'Code' = 4402; - 'Message' = 'Access to the directory was denied'; - 'Severity' = 'Error'; - 'Area' = 'Provider'; - }; - 'DirectoryFilterInvalid' = @{ - 'Code' = 4403; - 'Message' = 'A directory filter value is invalid'; - 'Severity' = 'Error'; - 'Area' = 'Provider'; - }; - 'DirectoryReadFailed' = @{ - 'Code' = 4404; - 'Message' = 'The directory could not be read'; - 'Severity' = 'Error'; - 'Area' = 'Provider'; - }; - 'DirectoryInformationCollected' = @{ - 'Code' = 4450; - 'Message' = 'The directory information was collected successfully'; - 'Severity' = 'Debug'; - 'Area' = 'Provider'; - }; - 'ProcessCounterReadFailed' = @{ - 'Code' = 4500; - 'Message' = 'The performance counters for the process information could not be read'; - 'Severity' = 'Error'; - 'Area' = 'Provider'; - }; - 'ProcessInformationCollected' = @{ - 'Code' = 4550; - 'Message' = 'The process information was collected successfully'; + 'ScheduledTaskInformationCollected' = @{ + 'Code' = 4650; + 'Message' = 'The scheduled task information was collected successfully'; 'Severity' = 'Debug'; 'Area' = 'Provider'; }; diff --git a/src/Plugins/Public/Invoke-IcingaCheckCPU.ps1 b/src/Plugins/Public/Invoke-IcingaCheckCPU.ps1 index 6f94a71..4612667 100644 --- a/src/Plugins/Public/Invoke-IcingaCheckCPU.ps1 +++ b/src/Plugins/Public/Invoke-IcingaCheckCPU.ps1 @@ -44,9 +44,9 @@ This plugin is Windows-only because it relies on the Windows performance counter | Critical | System.String | Critical threshold in percent, using the Icinga threshold grammar. | | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|-----------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | +| Name | Type | Description | Default | +|-----------|--------------|------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -54,7 +54,7 @@ This plugin is Windows-only because it relies on the Windows performance counter | NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | .OUTPUTS -System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). +System.Int32 -- The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). .EXAMPLE PS> Invoke-IcingaCheckCPU -Warning 80 -Critical 90 @@ -78,24 +78,25 @@ command wrapper is expected to exit with it. function Invoke-IcingaCheckCPU() { param ( - [string]$Warning = '', - [string]$Critical = '', - [int]$Verbosity = 0, - [switch]$NoPerfData = $false + [string]$Warning = '', + [string]$Critical = '', + [int]$Verbosity = 0, + [switch]$NoPerfData = $false ); - [string]$CounterPath = '\Processor Information(*)\% Processor Time'; + [string]$CounterPath = '\Processor Information(*)\% Processor Time'; # Literal declaration, so the counter discovery at module start finds and warms it. New-IcingaPerformanceCounter -Counter @('\Processor Information(*)\% Processor Time'); - $CheckPackage = New-IcingaPlugin 'CPU Load'; - $CheckPackage.Verbose = $Verbosity; + $CheckPackage = New-IcingaPlugin 'CPU Load'; + $CheckPackage.Verbose = $Verbosity; + $CheckPackage.NoPerfData = $NoPerfData; - $Counters = Get-IcingaPerformanceCounter -Counter $CounterPath -StructureByInstance; + $Counters = Get-IcingaPerformanceCounter -Counter $CounterPath -StructureByInstance; - [array]$Nodes = @(); - [hashtable]$NodeCores = @{ }; + [array]$Nodes = @(); + [hashtable]$NodeCores = @{ }; if ($null -ne $Counters) { # Natural order puts the nodes and the cores of every node in numeric order. @@ -109,7 +110,7 @@ function Invoke-IcingaCheckCPU() if ($NodeCores.ContainsKey($Parts[0]) -eq $false) { $NodeCores[$Parts[0]] = @(); - $Nodes += $Parts[0]; + $Nodes += $Parts[0]; } $NodeCores[$Parts[0]] += $Instance; @@ -128,15 +129,15 @@ function Invoke-IcingaCheckCPU() [int]$OverallCount = 0; foreach ($Node in $Nodes) { - $NodePackage = New-IcingaPlugin ([string]::Format('NUMA Node #{0}', $Node)); + $NodePackage = New-IcingaPlugin ([string]::Format('NUMA Node #{0}', $Node)); $CheckPackage.AddCheck($NodePackage).Commit(); [double]$NodeSum = 0; [int]$NodeCount = 0; foreach ($Instance in $NodeCores[$Node]) { - $Value = Get-IcingaPerformanceCounterValue -InputObject $Counters[$Instance]['Processor Information']['% Processor Time']; - $Entry = @{ + $Value = Get-IcingaPerformanceCounterValue -InputObject $Counters[$Instance]['Processor Information']['% Processor Time']; + $Entry = @{ 'Parent' = $NodePackage; 'Name' = [string]::Format('Core #{0}', $CoreNumber); 'Index' = [string]::Format('{0}_{1}', $Node, $CoreNumber); @@ -144,7 +145,7 @@ function Invoke-IcingaCheckCPU() 'Error' = $null; }; - $CoreNumber += 1; + $CoreNumber = $CoreNumber + 1; if ($null -eq $Value -or $Value -is [string]) { $Entry['Error'] = [string]$Value; @@ -198,11 +199,8 @@ function Invoke-IcingaCheckCPU() continue; } - $Check = New-IcingaPlugin $Entry['Name'] ([System.Math]::Round([double]$Entry['Value'], 2)) '%'; - $Check.NoPerfData = $NoPerfData; - $Entry['Parent'].AddCheck( - $Check. + (New-IcingaPlugin $Entry['Name'] ([System.Math]::Round([double]$Entry['Value'], 2)) '%'). MetricIndex($Entry['Index']). MetricLabel('load'). Warning($Warning). diff --git a/src/Plugins/Public/Invoke-IcingaCheckDirectory.ps1 b/src/Plugins/Public/Invoke-IcingaCheckDirectory.ps1 index 7502c54..9a4a91d 100644 --- a/src/Plugins/Public/Invoke-IcingaCheckDirectory.ps1 +++ b/src/Plugins/Public/Invoke-IcingaCheckDirectory.ps1 @@ -29,9 +29,9 @@ sizes in bytes. A directory that cannot be read or an invalid filter value is reported as UNKNOWN with its reason. .PARAMETER Path -| Name | Type | Description | Default | -|------|---------------|-----------------------------------------------|---------| -| Path | System.String | Directory to check, e.g. 'C:\ProgramData\Logs'. | | +| Name | Type | Description | Default | +|------|---------------|-------------------------------------------------|---------| +| Path | System.String | Directory to check, e.g. 'C:\ProgramData\Logs'. | | .PARAMETER FileNames | Name | Type | Description | Default | @@ -39,79 +39,79 @@ reported as UNKNOWN with its reason. | FileNames | System.Array | Wildcard patterns for the entry names, e.g. '*.log'. | @('*') | .PARAMETER Recurse -| Name | Type | Description | Default | -|---------|----------------------------------------------|----------------------------------|---------| -| Recurse | System.Management.Automation.SwitchParameter | Check every subdirectory as well. | False | +| Name | Type | Description | Default | +|---------|----------------------------------------------|-----------------------------------|---------| +| Recurse | System.Management.Automation.SwitchParameter | Check every subdirectory as well. | False | .PARAMETER Warning -| Name | Type | Description | Default | -|---------|---------------|----------------------------------------------------------|---------| -| Warning | System.String | Warning threshold for the number of matching files. | | +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------------------|---------| +| Warning | System.String | Warning threshold for the number of matching files. | | .PARAMETER Critical -| Name | Type | Description | Default | -|----------|---------------|----------------------------------------------------------|---------| -| Critical | System.String | Critical threshold for the number of matching files. | | +| Name | Type | Description | Default | +|----------|---------------|------------------------------------------------------|---------| +| Critical | System.String | Critical threshold for the number of matching files. | | .PARAMETER WarningTotalSize -| Name | Type | Description | Default | -|------------------|---------------|------------------------------------------------------|---------| -| WarningTotalSize | System.String | Warning threshold for the total size, e.g. '2GiB'. | | +| Name | Type | Description | Default | +|------------------|---------------|----------------------------------------------------|---------| +| WarningTotalSize | System.String | Warning threshold for the total size, e.g. '2GiB'. | | .PARAMETER CriticalTotalSize -| Name | Type | Description | Default | -|-------------------|---------------|------------------------------------------------------|---------| -| CriticalTotalSize | System.String | Critical threshold for the total size, e.g. '4GiB'. | | +| Name | Type | Description | Default | +|-------------------|---------------|-----------------------------------------------------|---------| +| CriticalTotalSize | System.String | Critical threshold for the total size, e.g. '4GiB'. | | .PARAMETER WarningSmallestFile -| Name | Type | Description | Default | -|---------------------|---------------|-------------------------------------------------|---------| -| WarningSmallestFile | System.String | Warning threshold for the smallest file size. | | +| Name | Type | Description | Default | +|---------------------|---------------|-----------------------------------------------|---------| +| WarningSmallestFile | System.String | Warning threshold for the smallest file size. | | .PARAMETER CriticalSmallestFile -| Name | Type | Description | Default | -|----------------------|---------------|-------------------------------------------------|---------| -| CriticalSmallestFile | System.String | Critical threshold for the smallest file size. | | +| Name | Type | Description | Default | +|----------------------|---------------|------------------------------------------------|---------| +| CriticalSmallestFile | System.String | Critical threshold for the smallest file size. | | .PARAMETER WarningLargestFile -| Name | Type | Description | Default | -|--------------------|---------------|------------------------------------------------|---------| -| WarningLargestFile | System.String | Warning threshold for the largest file size. | | +| Name | Type | Description | Default | +|--------------------|---------------|----------------------------------------------|---------| +| WarningLargestFile | System.String | Warning threshold for the largest file size. | | .PARAMETER CriticalLargestFile -| Name | Type | Description | Default | -|---------------------|---------------|------------------------------------------------|---------| -| CriticalLargestFile | System.String | Critical threshold for the largest file size. | | +| Name | Type | Description | Default | +|---------------------|---------------|-----------------------------------------------|---------| +| CriticalLargestFile | System.String | Critical threshold for the largest file size. | | .PARAMETER WarningAverageFile -| Name | Type | Description | Default | -|--------------------|---------------|------------------------------------------------|---------| -| WarningAverageFile | System.String | Warning threshold for the average file size. | | +| Name | Type | Description | Default | +|--------------------|---------------|----------------------------------------------|---------| +| WarningAverageFile | System.String | Warning threshold for the average file size. | | .PARAMETER CriticalAverageFile -| Name | Type | Description | Default | -|---------------------|---------------|------------------------------------------------|---------| -| CriticalAverageFile | System.String | Critical threshold for the average file size. | | +| Name | Type | Description | Default | +|---------------------|---------------|-----------------------------------------------|---------| +| CriticalAverageFile | System.String | Critical threshold for the average file size. | | .PARAMETER CountFolderAsFile -| Name | Type | Description | Default | -|-------------------|----------------------------------------------|------------------------------------------------|---------| -| CountFolderAsFile | System.Management.Automation.SwitchParameter | Add the matching folders to the file count. | False | +| Name | Type | Description | Default | +|-------------------|----------------------------------------------|---------------------------------------------|---------| +| CountFolderAsFile | System.Management.Automation.SwitchParameter | Add the matching folders to the file count. | False | .PARAMETER ShowFileList -| Name | Type | Description | Default | -|--------------|----------------------------------------------|--------------------------------------------------------------|---------| -| ShowFileList | System.Management.Automation.SwitchParameter | List every matching entry; can make the output very large. | False | +| Name | Type | Description | Default | +|--------------|----------------------------------------------|------------------------------------------------------------|---------| +| ShowFileList | System.Management.Automation.SwitchParameter | List every matching entry; can make the output very large. | False | .PARAMETER ChangeTimeEqual -| Name | Type | Description | Default | -|-----------------|---------------|---------------------------------------------------------------|---------| -| ChangeTimeEqual | System.String | Only entries last written on the day this long ago, e.g. '1d'. | | +| Name | Type | Description | Default | +|-----------------|---------------|----------------------------------------------------------------|---------| +| ChangeTimeEqual | System.String | Only entries last written on the day this long ago, e.g. '1d'. | | .PARAMETER ChangeYoungerThan -| Name | Type | Description | Default | -|-------------------|---------------|-----------------------------------------------------------|---------| -| ChangeYoungerThan | System.String | Only entries last written within this duration, e.g. '5d'. | | +| Name | Type | Description | Default | +|-------------------|---------------|------------------------------------------------------------|---------| +| ChangeYoungerThan | System.String | Only entries last written within this duration, e.g. '5d'. | | .PARAMETER ChangeOlderThan | Name | Type | Description | Default | @@ -129,14 +129,14 @@ reported as UNKNOWN with its reason. | CreationOlderThan | System.String | Only entries created longer ago than this, e.g. '10d'. | | .PARAMETER CreationYoungerThan -| Name | Type | Description | Default | -|---------------------|---------------|------------------------------------------------------|---------| -| CreationYoungerThan | System.String | Only entries created within this duration, e.g. '5d'. | | +| Name | Type | Description | Default | +|---------------------|---------------|-------------------------------------------------------|---------| +| CreationYoungerThan | System.String | Only entries created within this duration, e.g. '5d'. | | .PARAMETER AccessYoungerThan -| Name | Type | Description | Default | -|-------------------|---------------|------------------------------------------------------------|---------| -| AccessYoungerThan | System.String | Only entries last accessed within this duration, e.g. '5d'. | | +| Name | Type | Description | Default | +|-------------------|---------------|-------------------------------------------------------------|---------| +| AccessYoungerThan | System.String | Only entries last accessed within this duration, e.g. '5d'. | | .PARAMETER AccessOlderThan | Name | Type | Description | Default | @@ -144,24 +144,24 @@ reported as UNKNOWN with its reason. | AccessOlderThan | System.String | Only entries last accessed longer ago than this, e.g. '10d'. | | .PARAMETER FileSizeGreaterThan -| Name | Type | Description | Default | -|---------------------|---------------|----------------------------------------------|---------| -| FileSizeGreaterThan | System.String | Only files larger than this size, e.g. '20MB'. | | +| Name | Type | Description | Default | +|---------------------|---------------|------------------------------------------------|---------| +| FileSizeGreaterThan | System.String | Only files larger than this size, e.g. '20MB'. | | .PARAMETER FileSizeSmallerThan -| Name | Type | Description | Default | -|---------------------|---------------|----------------------------------------------|---------| -| FileSizeSmallerThan | System.String | Only files smaller than this size, e.g. '5MB'. | | +| Name | Type | Description | Default | +|---------------------|---------------|------------------------------------------------|---------| +| FileSizeSmallerThan | System.String | Only files smaller than this size, e.g. '5MB'. | | .PARAMETER OverrideNotFound -| Name | Type | Description | Default | -|------------------|---------------|-----------------------------------------------------------------------------|---------| -| OverrideNotFound | System.String | State when nothing matches: Ok, Warning, Critical, Unknown; a missing path counts as empty. | | +| Name | Type | Description | Default | +|------------------|---------------|---------------------------------------------------------------------------------------------|---------| +| OverrideNotFound | System.String | State when nothing matches: Ok, Warning, Critical, Unknown; a missing path counts as empty. | | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|-----------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | +| Name | Type | Description | Default | +|-----------|--------------|------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -169,7 +169,7 @@ reported as UNKNOWN with its reason. | NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | .OUTPUTS -System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). +System.Int32 -- The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). .EXAMPLE PS> Invoke-IcingaCheckDirectory -Path 'C:\Users\Icinga\Downloads' -Warning 20 -Critical 30 @@ -230,8 +230,9 @@ function Invoke-IcingaCheckDirectory() $Verbosity = 2; } - $CheckPackage = New-IcingaPlugin ([string]::Format('Directory Check: "{0}"', $Path)); - $CheckPackage.Verbose = $Verbosity; + $CheckPackage = New-IcingaPlugin ([string]::Format('Directory Check: "{0}"', $Path)); + $CheckPackage.Verbose = $Verbosity; + $CheckPackage.NoPerfData = $NoPerfData; [hashtable]$DirectoryArguments = @{ 'Path' = $Path; @@ -251,7 +252,7 @@ function Invoke-IcingaCheckDirectory() 'IgnoreMissingPath' = ([string]::IsNullOrEmpty($OverrideNotFound) -eq $false); }; - $Directory = Get-IcingaDirectoryInformation @DirectoryArguments; + $Directory = Get-IcingaDirectoryInformation @DirectoryArguments; if (Test-IcingaError -InputObject $Directory) { return $CheckPackage.SetError($Directory).Compile(); @@ -274,12 +275,9 @@ function Invoke-IcingaCheckDirectory() ); foreach ($Metric in $Metrics) { - $Check = New-IcingaPlugin $Metric[0] $Metric[1] $Metric[2]; - $Check.NoPerfData = $NoPerfData; - # Perfdata label: ::ifw_directory:: (template auto-derived from the command). $CheckPackage.AddCheck( - $Check. + (New-IcingaPlugin $Metric[0] $Metric[1] $Metric[2]). MetricIndex($Path). MetricLabel($Metric[3]). Warning($Metric[4]). @@ -294,27 +292,21 @@ function Invoke-IcingaCheckDirectory() $FileFound = 'Yes'; } - $FoundCheck = New-IcingaPlugin 'File Found' $FileFound; - $FoundCheck.NoPerfData = $true; + $FoundCheck = (New-IcingaPlugin 'File Found' $FileFound).SetNoPerfData($true); if ([string]::IsNullOrEmpty($OverrideNotFound)) { $FoundCheck.SetNotice($FileFound).Commit(); - } elseif ($FileCount -ne 0 -or $OverrideNotFound -eq 'Ok') { + } elseif ($FileCount -ne 0) { $FoundCheck.SetOk($FileFound, $true).Commit(); - } elseif ($OverrideNotFound -eq 'Warning') { - $FoundCheck.SetWarning($FileFound, $true).Commit(); - } elseif ($OverrideNotFound -eq 'Critical') { - $FoundCheck.SetCritical($FileFound, $true).Commit(); } else { - $FoundCheck.SetUnknown($FileFound, $true).Commit(); + $FoundCheck.SetState($OverrideNotFound, $FileFound, $true).Commit(); } $CheckPackage.AddCheck($FoundCheck).Commit(); if ($ShowFileList) { - $FileListPackage = New-IcingaPlugin 'File List'; - $FileListPackage.IsNotice = $true; - $UnitType = 'IcingaUnit' -as [type]; + $FileListPackage = (New-IcingaPlugin 'File List').SetNotice(); + $UnitType = 'IcingaUnit' -as [type]; foreach ($Entry in (ConvertTo-IcingaSortedArray -InputObject @($Directory.FileList) -Property 'FullName')) { [string]$Details = 'Folder'; diff --git a/src/Plugins/Public/Invoke-IcingaCheckMemory.ps1 b/src/Plugins/Public/Invoke-IcingaCheckMemory.ps1 index 862cc79..baa0bf3 100644 --- a/src/Plugins/Public/Invoke-IcingaCheckMemory.ps1 +++ b/src/Plugins/Public/Invoke-IcingaCheckMemory.ps1 @@ -67,9 +67,9 @@ as UNKNOWN with its reason. | ExcludePageFile | System.Array | Skip page files matching these names (wildcards). | @() | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|-----------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | +| Name | Type | Description | Default | +|-----------|--------------|------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -77,7 +77,7 @@ as UNKNOWN with its reason. | NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | .OUTPUTS -System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). +System.Int32 -- The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). .EXAMPLE PS> Invoke-IcingaCheckMemory -Warning '80%' -Critical '90%' @@ -113,10 +113,11 @@ function Invoke-IcingaCheckMemory() # Literal declaration, so the counter discovery at module start finds and warms them. New-IcingaPerformanceCounter -Counter @('\Memory\Available Bytes', '\Memory\Pages/sec'); - $CheckPackage = New-IcingaPlugin 'Memory Usage'; - $CheckPackage.Verbose = $Verbosity; + $CheckPackage = New-IcingaPlugin 'Memory Usage'; + $CheckPackage.Verbose = $Verbosity; + $CheckPackage.NoPerfData = $NoPerfData; - $ComputerSystem = Get-IcingaWindowsInformation -ClassName 'Win32_ComputerSystem' -Property 'TotalPhysicalMemory', 'AutomaticManagedPagefile'; + $ComputerSystem = Get-IcingaWindowsInformation -ClassName 'Win32_ComputerSystem' -Property 'TotalPhysicalMemory', 'AutomaticManagedPagefile'; if (Test-IcingaError -InputObject $ComputerSystem) { return $CheckPackage.SetError($ComputerSystem).Compile(); @@ -147,12 +148,10 @@ function Invoke-IcingaCheckMemory() (New-IcingaPlugin 'Used Memory').SetError('Failed to read the performance counter \Memory\Available Bytes: {0}', $Available) ).Commit(); } else { - [uint64]$UsedMemory = [System.Math]::Max([double]0, [double]$TotalMemory - [double]$Available); - $MemoryCheck = New-IcingaPlugin 'Used Memory' $UsedMemory 'B'; - $MemoryCheck.NoPerfData = $NoPerfData; + [uint64]$UsedMemory = [System.Math]::Max([double]0, [double]$TotalMemory - [double]$Available); $CheckPackage.AddCheck( - $MemoryCheck. + (New-IcingaPlugin 'Used Memory' $UsedMemory 'B'). MetricIndex('memory'). MetricLabel('used'). Warning($Warning). @@ -171,11 +170,8 @@ function Invoke-IcingaCheckMemory() (New-IcingaPlugin 'Memory pages/sec').SetError('Failed to read the performance counter \Memory\Pages/sec: {0}', $PagesSec) ).Commit(); } else { - $PagesCheck = New-IcingaPlugin 'Memory pages/sec' ([System.Math]::Round([double]$PagesSec, 2)); - $PagesCheck.NoPerfData = $NoPerfData; - $CheckPackage.AddCheck( - $PagesCheck. + (New-IcingaPlugin 'Memory pages/sec' ([System.Math]::Round([double]$PagesSec, 2))). MetricIndex('memory'). MetricLabel('pagessec'). Warning($MemoryPagesSecWarning). @@ -214,14 +210,12 @@ function Invoke-IcingaCheckMemory() $SizeMB = $MaximumSizes[$PageFileName]; } - [uint64]$Size = $SizeMB * 1MB; - [uint64]$Usage = [uint64]$PageFile.CurrentUsage * 1MB; - $PageFileCheck = New-IcingaPlugin $PageFileName $Usage 'B'; - $PageFileCheck.NoPerfData = $NoPerfData; + [uint64]$Size = $SizeMB * 1MB; + [uint64]$Usage = [uint64]$PageFile.CurrentUsage * 1MB; # Perfdata label: ::ifw_pagefile::used (own template instead of ifw_memory). $PageFilePackage.AddCheck( - $PageFileCheck. + (New-IcingaPlugin $PageFileName $Usage 'B'). MetricIndex($PageFileName). MetricName('pagefile'). MetricLabel('used'). diff --git a/src/Plugins/Public/Invoke-IcingaCheckPartitionSpace.ps1 b/src/Plugins/Public/Invoke-IcingaCheckPartitionSpace.ps1 index ee3137a..3530b30 100644 --- a/src/Plugins/Public/Invoke-IcingaCheckPartitionSpace.ps1 +++ b/src/Plugins/Public/Invoke-IcingaCheckPartitionSpace.ps1 @@ -26,14 +26,14 @@ A failed volume query is reported as UNKNOWN with its reason. This plugin is Windows-only because it relies on the Win32_Volume CIM class. .PARAMETER Warning -| Name | Type | Description | Default | -|---------|---------------|-----------------------------------------------------------------------------|---------| -| Warning | System.String | Warning threshold as percentage, size or Icinga range, e.g. '80%' or '400GB'. | | +| Name | Type | Description | Default | +|---------|---------------|-------------------------------------------------------------------------------|---------| +| Warning | System.String | Warning threshold as percentage, size or Icinga range, e.g. '80%' or '400GB'. | | .PARAMETER Critical -| Name | Type | Description | Default | -|----------|---------------|-----------------------------------------------------------------------------|---------| -| Critical | System.String | Critical threshold as percentage, size or Icinga range, e.g. '90%' or '450GB'. | | +| Name | Type | Description | Default | +|----------|---------------|--------------------------------------------------------------------------------|---------| +| Critical | System.String | Critical threshold as percentage, size or Icinga range, e.g. '90%' or '450GB'. | | .PARAMETER Include | Name | Type | Description | Default | @@ -41,9 +41,9 @@ Windows-only because it relies on the Win32_Volume CIM class. | Include | System.Array | Only check partitions matching these letters or labels (wildcards). | @() | .PARAMETER Exclude -| Name | Type | Description | Default | -|---------|--------------|--------------------------------------------------------------|---------| -| Exclude | System.Array | Skip partitions matching these letters or labels (wildcards). | @() | +| Name | Type | Description | Default | +|---------|--------------|---------------------------------------------------------------|---------| +| Exclude | System.Array | Skip partitions matching these letters or labels (wildcards). | @() | .PARAMETER RequiredPartition | Name | Type | Description | Default | @@ -51,9 +51,9 @@ Windows-only because it relies on the Win32_Volume CIM class. | RequiredPartition | System.Array | Partitions that must exist; a missing one is reported CRITICAL. | @() | .PARAMETER CheckFreeSpace -| Name | Type | Description | Default | -|----------------|----------------------------------------------|---------------------------------------------------|---------| -| CheckFreeSpace | System.Management.Automation.SwitchParameter | Evaluate the free instead of the used space. | False | +| Name | Type | Description | Default | +|----------------|----------------------------------------------|----------------------------------------------|---------| +| CheckFreeSpace | System.Management.Automation.SwitchParameter | Evaluate the free instead of the used space. | False | .PARAMETER IgnoreEmptyChecks | Name | Type | Description | Default | @@ -66,9 +66,9 @@ Windows-only because it relies on the Win32_Volume CIM class. | SkipUnknown | System.Management.Automation.SwitchParameter | Report OK instead of UNKNOWN for a volume without size data. | False | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|-----------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | +| Name | Type | Description | Default | +|-----------|--------------|------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -76,7 +76,7 @@ Windows-only because it relies on the Win32_Volume CIM class. | NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | .OUTPUTS -System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). +System.Int32 -- The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). .EXAMPLE PS> Invoke-IcingaCheckPartitionSpace -Warning '80%' -Critical '90%' @@ -121,10 +121,11 @@ function Invoke-IcingaCheckPartitionSpace() $MetricLabel = 'free'; } - $CheckPackage = New-IcingaPlugin $PackageName; - $CheckPackage.Verbose = $Verbosity; + $CheckPackage = New-IcingaPlugin $PackageName; + $CheckPackage.Verbose = $Verbosity; + $CheckPackage.NoPerfData = $NoPerfData; - $Volumes = Get-IcingaDiskInformation -Entrypoint 'Volume'; + $Volumes = Get-IcingaDiskInformation -Entrypoint 'Volume'; if (Test-IcingaError -InputObject $Volumes) { return $CheckPackage.SetError($Volumes).Compile(); @@ -183,12 +184,9 @@ function Invoke-IcingaCheckPartitionSpace() $Value = $Volume.FreeSpace; } - $PartitionCheck = New-IcingaPlugin $CheckName $Value 'B'; - $PartitionCheck.NoPerfData = $NoPerfData; - # Perfdata label: ::ifw_partitionspace::used|free (template auto-derived from the command). $CheckPackage.AddCheck( - $PartitionCheck. + (New-IcingaPlugin $CheckName $Value 'B'). MetricIndex($PartitionName). MetricLabel($MetricLabel). Warning($Warning). @@ -200,7 +198,7 @@ function Invoke-IcingaCheckPartitionSpace() ).Commit(); } - $CheckPackage.AddMissingChecks($RequiredPartition, $KnownPartitions, 'Partition {0}', 'Mandatory partition not found on host', 2, '[:\\/]+$').Commit(); + $CheckPackage.AddMissingChecks($RequiredPartition, $KnownPartitions, 'Partition {0}', 'Mandatory partition not found on host', 'Critical', '[:\\/]+$').Commit(); if ($CheckPackage.HasChecks() -eq $false) { if ($IgnoreEmptyChecks) { diff --git a/src/Plugins/Public/Invoke-IcingaCheckPerfCounter.ps1 b/src/Plugins/Public/Invoke-IcingaCheckPerfCounter.ps1 index 366545c..59e5051 100644 --- a/src/Plugins/Public/Invoke-IcingaCheckPerfCounter.ps1 +++ b/src/Plugins/Public/Invoke-IcingaCheckPerfCounter.ps1 @@ -36,39 +36,39 @@ with '%' spelled out as 'percent', for example 'memory::ifw_perfcounter::availablebytes' for a counter without an instance. .PARAMETER PerfCounter -| Name | Type | Description | Default | -|-------------|--------------|------------------------------------------------------------------------|---------| -| PerfCounter | System.Array | Counter paths to check, e.g. '\Processor(*)\% Processor Time'. | @() | +| Name | Type | Description | Default | +|-------------|--------------|---------------------------------------------------------------|---------| +| PerfCounter | System.Array | Counter paths to check, e.g. '\Processor(*)\% Processor Time'.| @() | .PARAMETER Warning -| Name | Type | Description | Default | -|---------|---------------|----------------------------------------------------------|---------| -| Warning | System.String | Warning threshold in the counter's unit, e.g. '80', '500MB' or '30m'. | | +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------------------------------------|---------| +| Warning | System.String | Warning threshold in the counter's unit, e.g. '80', '500MB' or '30m'. | | .PARAMETER Critical -| Name | Type | Description | Default | -|----------|---------------|----------------------------------------------------------|---------| -| Critical | System.String | Critical threshold in the counter's unit, e.g. '90', '1GB' or '1h'. | | +| Name | Type | Description | Default | +|----------|---------------|---------------------------------------------------------------------|---------| +| Critical | System.String | Critical threshold in the counter's unit, e.g. '90', '1GB' or '1h'. | | .PARAMETER IncludeCounter -| Name | Type | Description | Default | -|----------------|--------------|--------------------------------------------------------------|---------| -| IncludeCounter | System.Array | Only check instance paths matching these patterns. | @() | +| Name | Type | Description | Default | +|----------------|--------------|----------------------------------------------------|---------| +| IncludeCounter | System.Array | Only check instance paths matching these patterns. | @() | .PARAMETER ExcludeCounter -| Name | Type | Description | Default | -|----------------|--------------|--------------------------------------------------------------|---------| -| ExcludeCounter | System.Array | Skip instance paths matching these patterns. | @() | +| Name | Type | Description | Default | +|----------------|--------------|----------------------------------------------|---------| +| ExcludeCounter | System.Array | Skip instance paths matching these patterns. | @() | .PARAMETER IgnoreEmptyChecks -| Name | Type | Description | Default | -|-------------------|----------------------------------------------|--------------------------------------------------------------|---------| -| IgnoreEmptyChecks | System.Management.Automation.SwitchParameter | Return OK instead of UNKNOWN when no counter remains to check. | False | +| Name | Type | Description | Default | +|-------------------|----------------------------------------------|----------------------------------------------------------------|---------| +| IgnoreEmptyChecks | System.Management.Automation.SwitchParameter | Return OK instead of UNKNOWN when no counter remains to check. | False | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|-----------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | +| Name | Type | Description | Default | +|-----------|--------------|------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -76,7 +76,7 @@ with '%' spelled out as 'percent', for example | NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | .OUTPUTS -System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). +System.Int32 -- The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). .EXAMPLE PS> Invoke-IcingaCheckPerfCounter -PerfCounter '\Processor(*)\% Processor Time' -Warning 80 -Critical 90 -ExcludeCounter '*_Total*' @@ -106,10 +106,11 @@ function Invoke-IcingaCheckPerfCounter() [switch]$NoPerfData = $false ); - $CheckPackage = New-IcingaPlugin 'Performance Counter'; - $CheckPackage.Verbose = $Verbosity; + $CheckPackage = New-IcingaPlugin 'Performance Counter'; + $CheckPackage.Verbose = $Verbosity; + $CheckPackage.NoPerfData = $NoPerfData; - [array]$Requested = @(); + [array]$Requested = @(); foreach ($CounterPath in $PerfCounter) { if ([string]::IsNullOrEmpty([string]$CounterPath) -eq $false) { @@ -130,7 +131,7 @@ function Invoke-IcingaCheckPerfCounter() ); [array]$TimeTypes = @( 'AverageTimer32', 'ElapsedTime' ); - $Counters = Get-IcingaPerformanceCounter -Counter $Requested; + $Counters = Get-IcingaPerformanceCounter -Counter $Requested; if ($null -eq $Counters) { return $CheckPackage.SetError('Failed to read the performance counters {0}', ($Requested -join ', ')).Compile(); @@ -184,7 +185,6 @@ function Invoke-IcingaCheckPerfCounter() # because the label sanitizing would drop it. $Instance = $CounterType::ParsePath($InstancePath); [string]$Label = $Instance.Counter.Replace('%', 'percent') + $Instance.Instance; - [string]$Type = [string]$Instances[$InstancePath]['type']; [string]$Unit = ''; [double]$Scale = 1; @@ -214,12 +214,9 @@ function Invoke-IcingaCheckPerfCounter() $Measured = [System.Math]::Round($Measured, 2); } - $Check = New-IcingaPlugin $InstancePath $Measured $Unit; - $Check.NoPerfData = $NoPerfData; - # Perfdata label: ::ifw_perfcounter:: (template auto-derived from the command). $CounterPackage.AddCheck( - $Check. + (New-IcingaPlugin $InstancePath $Measured $Unit). MetricIndex($Instance.Category). MetricLabel($Label). Warning($Warning). diff --git a/src/Plugins/Public/Invoke-IcingaCheckProcess.ps1 b/src/Plugins/Public/Invoke-IcingaCheckProcess.ps1 index 5c63012..73be18d 100644 --- a/src/Plugins/Public/Invoke-IcingaCheckProcess.ps1 +++ b/src/Plugins/Public/Invoke-IcingaCheckProcess.ps1 @@ -69,44 +69,44 @@ Performance data is written for the summary only, with the labels | ThreadCountCritical | System.String | Critical threshold for the thread count of each process. | | .PARAMETER TotalPageFileWarning -| Name | Type | Description | Default | -|----------------------|---------------|--------------------------------------------------------------------|---------| -| TotalPageFileWarning | System.String | Warning threshold for the page file usage of all processes of a name. | | +| Name | Type | Description | Default | +|----------------------|---------------|-----------------------------------------------------------------------|---------| +| TotalPageFileWarning | System.String | Warning threshold for the page file usage of all processes of a name. | | .PARAMETER TotalPageFileCritical -| Name | Type | Description | Default | -|-----------------------|---------------|--------------------------------------------------------------------|---------| -| TotalPageFileCritical | System.String | Critical threshold for the page file usage of all processes of a name. | | +| Name | Type | Description | Default | +|-----------------------|---------------|------------------------------------------------------------------------|---------| +| TotalPageFileCritical | System.String | Critical threshold for the page file usage of all processes of a name. | | .PARAMETER TotalMemoryWarning -| Name | Type | Description | Default | -|--------------------|---------------|-----------------------------------------------------------------|---------| -| TotalMemoryWarning | System.String | Warning threshold for the memory usage of all processes of a name. | | +| Name | Type | Description | Default | +|--------------------|---------------|--------------------------------------------------------------------|---------| +| TotalMemoryWarning | System.String | Warning threshold for the memory usage of all processes of a name. | | .PARAMETER TotalMemoryCritical -| Name | Type | Description | Default | -|---------------------|---------------|-----------------------------------------------------------------|---------| -| TotalMemoryCritical | System.String | Critical threshold for the memory usage of all processes of a name. | | +| Name | Type | Description | Default | +|---------------------|---------------|---------------------------------------------------------------------|---------| +| TotalMemoryCritical | System.String | Critical threshold for the memory usage of all processes of a name. | | .PARAMETER TotalCPUWarning -| Name | Type | Description | Default | -|-----------------|---------------|--------------------------------------------------------------|---------| -| TotalCPUWarning | System.String | Warning threshold for the CPU usage of all processes of a name. | | +| Name | Type | Description | Default | +|-----------------|---------------|-----------------------------------------------------------------|---------| +| TotalCPUWarning | System.String | Warning threshold for the CPU usage of all processes of a name. | | .PARAMETER TotalCPUCritical -| Name | Type | Description | Default | -|------------------|---------------|--------------------------------------------------------------|---------| -| TotalCPUCritical | System.String | Critical threshold for the CPU usage of all processes of a name. | | +| Name | Type | Description | Default | +|------------------|---------------|------------------------------------------------------------------|---------| +| TotalCPUCritical | System.String | Critical threshold for the CPU usage of all processes of a name. | | .PARAMETER TotalThreadCountWarning -| Name | Type | Description | Default | -|-------------------------|---------------|----------------------------------------------------------------|---------| -| TotalThreadCountWarning | System.String | Warning threshold for the thread count of all processes of a name. | | +| Name | Type | Description | Default | +|-------------------------|---------------|-------------------------------------------------------------------|---------| +| TotalThreadCountWarning | System.String | Warning threshold for the thread count of all processes of a name.| | .PARAMETER TotalThreadCountCritical -| Name | Type | Description | Default | -|--------------------------|---------------|----------------------------------------------------------------|---------| -| TotalThreadCountCritical | System.String | Critical threshold for the thread count of all processes of a name. | | +| Name | Type | Description | Default | +|--------------------------|---------------|--------------------------------------------------------------------|---------| +| TotalThreadCountCritical | System.String | Critical threshold for the thread count of all processes of a name.| | .PARAMETER TotalProcessCountWarning | Name | Type | Description | Default | @@ -119,24 +119,24 @@ Performance data is written for the summary only, with the labels | TotalProcessCountCritical | System.String | Critical threshold for the number of processes of a name. | | .PARAMETER Process -| Name | Type | Description | Default | -|---------|--------------|-----------------------------------------------------------------------|---------| -| Process | System.Array | Process names without '.exe' to check, wildcards allowed. Empty checks all. | @() | +| Name | Type | Description | Default | +|---------|--------------|-----------------------------------------------------------------------------|---------| +| Process | System.Array | Process names without '.exe' to check, wildcards allowed. Empty checks all. | @() | .PARAMETER ExcludeProcess -| Name | Type | Description | Default | -|----------------|--------------|----------------------------------------------------------|---------| -| ExcludeProcess | System.Array | Process names to skip, wildcards allowed. | @() | +| Name | Type | Description | Default | +|----------------|--------------|-------------------------------------------|---------| +| ExcludeProcess | System.Array | Process names to skip, wildcards allowed. | @() | .PARAMETER OverrideNotFound -| Name | Type | Description | Default | -|------------------|---------------|------------------------------------------------------------------------|---------| -| OverrideNotFound | System.String | State for a Process entry without a match: Ok, Warning, Critical or Unknown. | Unknown | +| Name | Type | Description | Default | +|------------------|---------------|-------------------------------------------------------------------------------|---------| +| OverrideNotFound | System.String | State for a Process entry without a match: Ok, Warning, Critical or Unknown. | Unknown | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|-----------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | +| Name | Type | Description | Default | +|-----------|--------------|------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -144,7 +144,7 @@ Performance data is written for the summary only, with the labels | NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | .OUTPUTS -System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). +System.Int32 -- The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). .EXAMPLE PS> Invoke-IcingaCheckProcess -Process 'powershell' -Verbosity 2 @@ -192,10 +192,11 @@ function Invoke-IcingaCheckProcess() [switch]$NoPerfData = $false ); - $CheckPackage = New-IcingaPlugin 'Process Overview'; - $CheckPackage.Verbose = $Verbosity; + $CheckPackage = New-IcingaPlugin 'Process Overview'; + $CheckPackage.Verbose = $Verbosity; + $CheckPackage.NoPerfData = $NoPerfData; - $Data = Get-IcingaProcessInformation -Include $Process -Exclude $ExcludeProcess; + $Data = Get-IcingaProcessInformation -Include $Process -Exclude $ExcludeProcess; if (Test-IcingaError -InputObject $Data) { return $CheckPackage.SetError($Data).Compile(); @@ -235,8 +236,12 @@ function Invoke-IcingaCheckProcess() foreach ($Package in $Packages) { foreach ($Metric in $Package[1]) { - $Check = New-IcingaPlugin $Metric[0] $Metric[1] $Metric[2]; - $Check.NoPerfData = ($NoPerfData -or [string]::IsNullOrEmpty($Metric[6])); + $Check = (New-IcingaPlugin $Metric[0] $Metric[1] $Metric[2]). + SetNoPerfData([string]::IsNullOrEmpty($Metric[6])). + MetricIndex($Name). + MetricLabel($Metric[6]). + Warning($Metric[4]). + Critical($Metric[5]); # Counts have no size to calculate percentages from. if ([double]$Metric[3] -gt 0) { @@ -244,14 +249,7 @@ function Invoke-IcingaCheckProcess() } # Perfdata label: ::ifw_process:: (template auto-derived from the command). - $Package[0].AddCheck( - $Check. - MetricIndex($Name). - MetricLabel($Metric[6]). - Warning($Metric[4]). - Critical($Metric[5]). - CheckRange() - ).Commit(); + $Package[0].AddCheck($Check.CheckRange()).Commit(); } $ProcessPackage.AddCheck($Package[0]).Commit(); @@ -260,16 +258,9 @@ function Invoke-IcingaCheckProcess() $CheckPackage.AddCheck($ProcessPackage).Commit(); } - [hashtable]$NotFoundStates = @{ - 'Ok' = 0; - 'Warning' = 1; - 'Critical' = 2; - 'Unknown' = 3; - }; - # Wildcard entries are reported as well: a pattern without any match means the # expected process is not running. - $CheckPackage.AddMissingChecks($Process, @($Data.Processes.Keys), '{0}', 'Process not found', $NotFoundStates[$OverrideNotFound]).Commit(); + $CheckPackage.AddMissingChecks($Process, @($Data.Processes.Keys), '{0}', 'Process not found', $OverrideNotFound).Commit(); if ($CheckPackage.HasChecks() -eq $false) { return $CheckPackage.SetError('No process matches the given filter').Compile(); diff --git a/src/Plugins/Public/Invoke-IcingaCheckScheduledTask.ps1 b/src/Plugins/Public/Invoke-IcingaCheckScheduledTask.ps1 new file mode 100644 index 0000000..e597efd --- /dev/null +++ b/src/Plugins/Public/Invoke-IcingaCheckScheduledTask.ps1 @@ -0,0 +1,275 @@ +<# +.SYNOPSIS +Check the state, exit code, missed runs and run times of Windows scheduled tasks + +.DESCRIPTION +Reads scheduled tasks through Get-IcingaScheduledTask and builds an IcingaPlugin +container named 'Scheduled Tasks' grouped by task path. Each task becomes a child +package containing checks for its State, Missed Runs, Last Task Result, Last Run +Time and Next Run Time. State is compared against the allowed State list (when +provided) using CheckNotIn, raising CRITICAL when the task is not in any of the +expected states. Missed Runs is evaluated against WarningMissedRuns and +CriticalMissedRuns using the Icinga range grammar. Last Task Result raises +CRITICAL whenever the last exit code is non-zero, unless IgnoreLastRunTime is set +or the exit code is listed in IgnoreExitCodes (decimal and hex representations +such as '0x41301' are both accepted). Last Run Time and Next Run Time measure the +offset in seconds between the current time and the timestamp (Last Run Time +counts up since the last execution, Next Run Time counts down until the next +scheduled execution, and 0s is rendered as 'Never' when unset) and are evaluated +against their respective duration thresholds. + +Explicit task names in TaskName (without wildcards) that do not exist on the host +are reported with the state chosen by OverrideNotFound (UNKNOWN by default). When +no task matches the filter at all, the plugin returns UNKNOWN, or OK when +MitigateUnknown is set. + +Performance data uses the labels '::ifw_scheduledtask::state', +'::missedruns', '::lasttaskresult', '::lastruntime' and '::nextruntime'. + +.PARAMETER TaskName +| Name | Type | Description | Default | +|----------|--------------|-------------------------------------------------------------------------------|---------| +| TaskName | System.Array | Task names to check (wildcards allowed; plain names must exist). | @() | + +.PARAMETER ExcludeTaskName +| Name | Type | Description | Default | +|-----------------|--------------|------------------------------------------------------------------------|---------| +| ExcludeTaskName | System.Array | Task names to exclude from the check (wildcards allowed). | @() | + +.PARAMETER TaskPath +| Name | Type | Description | Default | +|----------|--------------|-------------------------------------------------------------------------------|---------| +| TaskPath | System.Array | Task folder paths to include (wildcards allowed, e.g. '\Icinga\*'). | @() | + +.PARAMETER ExcludeTaskPath +| Name | Type | Description | Default | +|-----------------|--------------|------------------------------------------------------------------------|---------| +| ExcludeTaskPath | System.Array | Task folder paths to exclude (wildcards allowed). | @() | + +.PARAMETER State +| Name | Type | Description | Default | +|-------|-----------------------------|----------------------------------------------------------------------------|---------| +| State | IcingaScheduledTaskStatus[] | Allowed task states ('Unknown', 'Disabled', 'Queued', 'Ready', 'Running'). | @() | + +.PARAMETER IgnoreExitCodes +| Name | Type | Description | Default | +|-----------------|--------------|------------------------------------------------------------------------|---------| +| IgnoreExitCodes | System.Array | Non-zero task exit codes to treat as OK (decimal or hex, e.g. 267009). | @() | + +.PARAMETER WarningMissedRuns +| Name | Type | Description | Default | +|-------------------|---------------|---------------------------------------------------------------------|---------| +| WarningMissedRuns | System.String | Warning threshold for the number of missed runs. | | + +.PARAMETER CriticalMissedRuns +| Name | Type | Description | Default | +|--------------------|---------------|--------------------------------------------------------------------|---------| +| CriticalMissedRuns | System.String | Critical threshold for the number of missed runs. | | + +.PARAMETER WarningLastRunTime +| Name | Type | Description | Default | +|--------------------|---------------|--------------------------------------------------------------------|---------| +| WarningLastRunTime | System.String | Warning threshold for the age of the last run (e.g. '1d', '12h'). | | + +.PARAMETER CriticalLastRunTime +| Name | Type | Description | Default | +|---------------------|---------------|-------------------------------------------------------------------|---------| +| CriticalLastRunTime | System.String | Critical threshold for the age of the last run (e.g. '2d', '24h').| | + +.PARAMETER WarningNextRunTime +| Name | Type | Description | Default | +|--------------------|---------------|--------------------------------------------------------------------|---------| +| WarningNextRunTime | System.String | Warning threshold for the next run offset (e.g. '10m', '-1h:'). | | + +.PARAMETER CriticalNextRunTime +| Name | Type | Description | Default | +|---------------------|---------------|-------------------------------------------------------------------|---------| +| CriticalNextRunTime | System.String | Critical threshold for the next run offset (e.g. '30m', '-2h:'). | | + +.PARAMETER IgnoreLastRunTime +| Name | Type | Description | Default | +|-------------------|----------------------------------------------|----------------------------------------------------|---------| +| IgnoreLastRunTime | System.Management.Automation.SwitchParameter | Do not alert on non-zero Last Task Result codes. | False | + +.PARAMETER MitigateUnknown +| Name | Type | Description | Default | +|-----------------|----------------------------------------------|--------------------------------------------------------------|---------| +| MitigateUnknown | System.Management.Automation.SwitchParameter | Return OK instead of UNKNOWN when no task matches the filter.| False | + +.PARAMETER OverrideNotFound +| Name | Type | Description | Default | +|------------------|---------------|---------------------------------------------------------------------------|---------| +| OverrideNotFound | System.String | State for missing required tasks ('Ok', 'Warning', 'Critical', 'Unknown').| Unknown | + +.PARAMETER Verbosity +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | + +.PARAMETER NoPerfData +| Name | Type | Description | Default | +|------------|----------------------------------------------|---------------------------------------|---------| +| NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | + +.OUTPUTS +System.Int32 -- The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). + +.EXAMPLE +PS> Invoke-IcingaCheckScheduledTask -TaskName 'AutomaticBackup', 'Windows Backup Monitor' -State 'Ready' + +Checks that both backup tasks exist and are in the Ready state. + +.EXAMPLE +PS> Invoke-IcingaCheckScheduledTask -TaskPath '\Icinga\*' -State 'Ready', 'Running' -WarningLastRunTime '1d' -Verbosity 2 + +Checks all tasks under \Icinga\ for Ready or Running state and warns if a task has not run within the last day. + +.NOTES +Windows-only. Queries tasks through Get-IcingaScheduledTask. The integer exit code +is the return value; an Icinga command wrapper is expected to exit with it. +#> +function Invoke-IcingaCheckScheduledTask() +{ + param ( + [array]$TaskName = @(), + [array]$ExcludeTaskName = @(), + [array]$TaskPath = @(), + [array]$ExcludeTaskPath = @(), + [IcingaScheduledTaskStatus[]]$State = @(), + [array]$IgnoreExitCodes = @(), + [string]$WarningMissedRuns = '', + [string]$CriticalMissedRuns = '', + [string]$WarningLastRunTime = '', + [string]$CriticalLastRunTime = '', + [string]$WarningNextRunTime = '', + [string]$CriticalNextRunTime = '', + [switch]$IgnoreLastRunTime = $false, + [switch]$MitigateUnknown = $false, + [ValidateSet('Ok', 'Warning', 'Critical', 'Unknown')] + [string]$OverrideNotFound = 'Unknown', + [int]$Verbosity = 0, + [switch]$NoPerfData = $false + ); + + $CheckPackage = New-IcingaPlugin 'Scheduled Tasks'; + $CheckPackage.Verbose = $Verbosity; + $CheckPackage.NoPerfData = $NoPerfData; + + $Data = Get-IcingaScheduledTask -TaskName $TaskName -ExcludeTaskName $ExcludeTaskName -TaskPath $TaskPath -ExcludeTaskPath $ExcludeTaskPath; + + if (Test-IcingaError -InputObject $Data) { + return $CheckPackage.SetError($Data).Compile(); + } + + foreach ($PathKey in (ConvertTo-IcingaSortedArray -InputObject @($Data.Tasks.Keys))) { + $PathPackage = New-IcingaPlugin $PathKey; + + foreach ($Task in $Data.Tasks[$PathKey]) { + $TaskPackage = New-IcingaPlugin $Task.TaskName; + [string]$MetricIndex = ([string]::Format('{0}{1}', $Task.TaskPath, $Task.TaskName)).Trim('\').Replace('\', '_'); + + $TaskState = (New-IcingaPlugin 'State' $Task.State). + Translate(). + MetricIndex($MetricIndex). + MetricLabel('state'); + + if ($State.Count -ne 0) { + $TaskState.Critical($State).CheckNotIn().Commit(); + } + + $TaskMissedRuns = (New-IcingaPlugin 'Missed Runs' $Task.MissedRuns). + MetricIndex($MetricIndex). + MetricLabel('missedruns'); + + if ('' -ne $WarningMissedRuns -or '' -ne $CriticalMissedRuns) { + $TaskMissedRuns.Warning($WarningMissedRuns).Critical($CriticalMissedRuns).CheckRange().Commit(); + } + + $TaskLastResult = (New-IcingaPlugin 'Last Task Result' $Task.LastTaskResult). + MetricIndex($MetricIndex). + MetricLabel('lasttaskresult'); + + [bool]$ExitCodeIgnored = [bool]$IgnoreLastRunTime; + + if (-not $ExitCodeIgnored -and $Task.LastTaskResult -ne 0) { + [string]$ExitDecimal = [string]$Task.LastTaskResult; + [string]$ExitHex = [string]::Format('{0:X}', $Task.LastTaskResult); + [string]$ExitHex0x = [string]::Format('0x{0:X}', $Task.LastTaskResult); + + foreach ($IgnoredCode in $IgnoreExitCodes) { + [string]$CodeText = [string]$IgnoredCode; + if ($CodeText -ieq $ExitDecimal -or $CodeText -ieq $ExitHex -or $CodeText -ieq $ExitHex0x) { + $ExitCodeIgnored = $true; + break; + } + } + } + + if ($Task.LastTaskResult -ne 0 -and -not $ExitCodeIgnored) { + $TaskLastResult.SetCritical([string]::Format('Task exited with code {0}', $Task.LastTaskResult), $true).Commit(); + } + + [string]$LastRunDateText = $Task.LastRunTime; + if ([string]::IsNullOrEmpty($LastRunDateText)) { + $LastRunDateText = 'Never'; + } + + $TaskLastRunTime = (New-IcingaPlugin ([string]::Format('Last Run Time [{0}]', $LastRunDateText)) $Task.LastRunOffset 's'). + Translate(@{ 0 = 'Never' }). + MetricIndex($MetricIndex). + MetricLabel('lastruntime'); + + if ('' -ne $WarningLastRunTime -or '' -ne $CriticalLastRunTime) { + $TaskLastRunTime.Warning($WarningLastRunTime).Critical($CriticalLastRunTime).CheckRange().Commit(); + } + + [string]$NextRunDateText = $Task.NextRunTime; + if ([string]::IsNullOrEmpty($NextRunDateText)) { + $NextRunDateText = 'Never'; + } + + $TaskNextRunTime = (New-IcingaPlugin ([string]::Format('Next Run Time [{0}]', $NextRunDateText)) $Task.NextRunOffset 's'). + Translate(@{ 0 = 'Never' }). + MetricIndex($MetricIndex). + MetricLabel('nextruntime'); + + if ('' -ne $WarningNextRunTime -or '' -ne $CriticalNextRunTime) { + $TaskNextRunTime.Warning($WarningNextRunTime).Critical($CriticalNextRunTime).CheckRange().Commit(); + } + + $TaskPackage. + AddCheck($TaskState). + AddCheck($TaskMissedRuns). + AddCheck($TaskLastResult). + AddCheck($TaskLastRunTime). + AddCheck($TaskNextRunTime). + Commit(); + + $PathPackage.AddCheck($TaskPackage).Commit(); + } + + if ($PathPackage.HasChecks()) { + $CheckPackage.AddCheck($PathPackage).Commit(); + } + } + + [array]$RequiredTasks = @(); + + foreach ($Filter in $TaskName) { + if ([string]::IsNullOrEmpty([string]$Filter) -eq $false -and [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters([string]$Filter) -eq $false) { + $RequiredTasks += [string]$Filter; + } + } + + $CheckPackage.AddMissingChecks($RequiredTasks, $Data.TaskNames, '{0}', 'Task not found', $OverrideNotFound).Commit(); + + if ($CheckPackage.HasChecks() -eq $false) { + if ($MitigateUnknown) { + return $CheckPackage.SetOk('No scheduled task matches the given filter', $true).Compile(); + } + + return $CheckPackage.SetError('No scheduled task matches the given filter').Compile(); + } + + return $CheckPackage.Compile(); +} diff --git a/src/Plugins/Public/Invoke-IcingaCheckService.ps1 b/src/Plugins/Public/Invoke-IcingaCheckService.ps1 index 01c2252..a325c28 100644 --- a/src/Plugins/Public/Invoke-IcingaCheckService.ps1 +++ b/src/Plugins/Public/Invoke-IcingaCheckService.ps1 @@ -25,24 +25,24 @@ Unknown, 1 Stopped to 7 Paused) and per-state counters of all checked services This plugin is Windows-only because it relies on the Win32_Service CIM class. .PARAMETER Service -| Name | Type | Description | Default | -|---------|----------------|--------------------------------------------------------------------------|---------| -| Service | System.Array | Service names or display names to check, wildcards allowed. Empty checks all automatic services. | @() | +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------------------------------------------------------------|---------| +| Service | System.Array | Service names or display names to check, wildcards allowed. Empty checks all automatic services. | @() | .PARAMETER Exclude -| Name | Type | Description | Default | -|---------|--------------|---------------------------------------------------------------|---------| -| Exclude | System.Array | Service names or display names to skip, wildcards allowed. | @() | +| Name | Type | Description | Default | +|---------|--------------|------------------------------------------------------------|---------| +| Exclude | System.Array | Service names or display names to skip, wildcards allowed. | @() | .PARAMETER Status -| Name | Type | Description | Default | -|--------|---------------------|---------------------------------------------------------------------------------------------------|---------| -| Status | IcingaServiceStatus | Expected status of the given services: Stopped, StartPending, StopPending, Running, ContinuePending, PausePending, Paused or Unknown. | Running | +| Name | Type | Description | Default | +|--------|---------------------|--------------------------------------------------------------------------------------------------------------------------------------|---------| +| Status | IcingaServiceStatus | Expected status of the given services: Stopped, StartPending, StopPending, Running, ContinuePending, PausePending, Paused or Unknown.| Running | .PARAMETER FilterStartupType -| Name | Type | Description | Default | -|-------------------|----------------------------|-----------------------------------------------------------------------------------------------------|---------| -| FilterStartupType | IcingaServiceStartupType[] | Only check given services with one of these startup types: Boot, System, Automatic, Manual, Disabled, Unknown. | @() | +| Name | Type | Description | Default | +|-------------------|----------------------------|----------------------------------------------------------------------------------------------------------------|---------| +| FilterStartupType | IcingaServiceStartupType[] | Only check given services with one of these startup types: Boot, System, Automatic, Manual, Disabled, Unknown. | @() | .PARAMETER MitigateUnknown | Name | Type | Description | Default | @@ -50,19 +50,19 @@ This plugin is Windows-only because it relies on the Win32_Service CIM class. | MitigateUnknown | System.Management.Automation.SwitchParameter | Return OK instead of UNKNOWN when no service matches at all. | False | .PARAMETER OverrideNotOk -| Name | Type | Description | Default | -|---------------|---------------|-------------------------------------------------------------------------------|----------| +| Name | Type | Description | Default | +|---------------|---------------|---------------------------------------------------------------------------------|----------| | OverrideNotOk | System.String | State for a service not in the expected status: Ok, Warning, Critical, Unknown. | Critical | .PARAMETER OverrideNotFound -| Name | Type | Description | Default | -|------------------|---------------|--------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|------------------|---------------|--------------------------------------------------------------------------------|---------| | OverrideNotFound | System.String | State for a given service that does not exist: Ok, Warning, Critical, Unknown. | Unknown | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|-----------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | +| Name | Type | Description | Default | +|-----------|--------------|------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -70,7 +70,7 @@ This plugin is Windows-only because it relies on the Win32_Service CIM class. | NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | .OUTPUTS -System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). +System.Int32 -- The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). .EXAMPLE PS> Invoke-IcingaCheckService @@ -120,10 +120,11 @@ function Invoke-IcingaCheckService() ([IcingaServiceStatus]::Paused) = 'paused'; }; - $CheckPackage = New-IcingaPlugin 'Services'; - $CheckPackage.Verbose = $Verbosity; + $CheckPackage = New-IcingaPlugin 'Services'; + $CheckPackage.Verbose = $Verbosity; + $CheckPackage.NoPerfData = $NoPerfData; - $AllServices = Get-IcingaWindowsInformation -ClassName 'Win32_Service' -Property 'Name', 'DisplayName', 'State', 'StartMode', 'ExitCode'; + $AllServices = Get-IcingaWindowsInformation -ClassName 'Win32_Service' -Property 'Name', 'DisplayName', 'State', 'StartMode', 'ExitCode'; if (Test-IcingaError -InputObject $AllServices) { return $CheckPackage.SetError($AllServices).Compile(); @@ -136,7 +137,7 @@ function Invoke-IcingaCheckService() $KnownServices[[string]$ServiceEntry.DisplayName] = $true; } - $SummaryCount = [ordered]@{ + $SummaryCount = [ordered]@{ 'stopped' = 0; 'pendingstarted' = 0; 'pendingstopped' = 0; @@ -146,12 +147,11 @@ function Invoke-IcingaCheckService() 'paused' = 0; }; - $MetricPackage = New-IcingaPlugin 'Service Metrics'; - $MetricPackage.IsHidden = $true; - [bool]$AutoMode = ($Service.Count -eq 0); - [int]$ServiceCount = 0; - $StatusMap = 'IcingaServiceStatusMap' -as [type]; - $StartupTypeMap = 'IcingaServiceStartupTypeMap' -as [type]; + $MetricPackage = (New-IcingaPlugin 'Service Metrics').SetHidden(); + [bool]$AutoMode = ($Service.Count -eq 0); + [int]$ServiceCount = 0; + $StatusMap = 'IcingaServiceStatusMap' -as [type]; + $StartupTypeMap = 'IcingaServiceStartupTypeMap' -as [type]; foreach ($ServiceEntry in (ConvertTo-IcingaSortedArray -InputObject $AllServices -Property 'Name')) { [string]$ServiceName = $ServiceEntry.Name; @@ -186,22 +186,17 @@ function Invoke-IcingaCheckService() } } - $ServiceCheck = New-IcingaPlugin ([string]::Format('Service "{0} ({1})"', $DisplayName, $ServiceName)) ([string]$State); - - if ($OverrideNotOk -eq 'Warning') { - $ServiceCheck.Warning([string]$Expected).CheckNotEqual().Commit(); - } else { - $ServiceCheck.Critical([string]$Expected).CheckNotEqual().Commit(); - } + $ServiceCheck = (New-IcingaPlugin ([string]::Format('Service "{0} ({1})"', $DisplayName, $ServiceName)) $State). + MetricIndex($ServiceName). + MetricLabel('state'). + SetNoPerfData($AutoMode). + Critical([string]$Expected). + CheckNotEqual(); # An empty message keeps the comparison text; the lock stops the critical # comparison result from escalating the overridden state again. - if ($State -ne $Expected) { - if ($OverrideNotOk -eq 'Ok') { - $ServiceCheck.SetOk('', $true).Commit(); - } elseif ($OverrideNotOk -eq 'Unknown') { - $ServiceCheck.SetUnknown('', $true).Commit(); - } + if ($State -ne $Expected -and $OverrideNotOk -ne 'Critical') { + $ServiceCheck.SetState($OverrideNotOk, '', $true).Commit(); } $CheckPackage.AddCheck($ServiceCheck).Commit(); @@ -210,23 +205,8 @@ function Invoke-IcingaCheckService() if ($SummaryLabels.ContainsKey($State)) { $SummaryCount[$SummaryLabels[$State]] += 1; } - - if ($AutoMode -or $NoPerfData) { - continue; - } - - $MetricPackage.AddCheck( - (New-IcingaPlugin $ServiceName ([int]$State)).MetricIndex($ServiceName).MetricLabel('state').CheckRange() - ).Commit(); } - [hashtable]$NotFoundStates = @{ - 'Ok' = 0; - 'Warning' = 1; - 'Critical' = 2; - 'Unknown' = 3; - }; - # Wildcard arguments select services instead of naming one, so only plain # names can be missing. [array]$RequiredServices = @(); @@ -237,10 +217,8 @@ function Invoke-IcingaCheckService() } } - $CheckPackage.AddMissingChecks($RequiredServices, @($KnownServices.Keys), '{0}', 'Service not found', $NotFoundStates[$OverrideNotFound]).Commit(); + $CheckPackage.AddMissingChecks($RequiredServices, @($KnownServices.Keys), '{0}', 'Service not found', $OverrideNotFound).Commit(); - # The hidden metric package is attached only after this test, otherwise it would - # count as a check of an otherwise empty package. if ($CheckPackage.HasChecks() -eq $false) { if ($MitigateUnknown) { return $CheckPackage.SetOk('No service matches the given filter', $true).Compile(); @@ -249,19 +227,17 @@ function Invoke-IcingaCheckService() return $CheckPackage.SetError('No service matches the given filter').Compile(); } - if (-not $NoPerfData) { - foreach ($SummaryLabel in $SummaryCount.Keys) { - $MetricPackage.AddCheck( - (New-IcingaPlugin $SummaryLabel $SummaryCount[$SummaryLabel]).MetricIndex('summary').MetricLabel($SummaryLabel).CheckRange() - ).Commit(); - } - + foreach ($SummaryLabel in $SummaryCount.Keys) { $MetricPackage.AddCheck( - (New-IcingaPlugin 'count' $ServiceCount).MetricIndex('summary').MetricLabel('count').CheckRange() + (New-IcingaPlugin $SummaryLabel $SummaryCount[$SummaryLabel]).MetricIndex('summary').MetricLabel($SummaryLabel) ).Commit(); - - $CheckPackage.AddCheck($MetricPackage).Commit(); } + $MetricPackage.AddCheck( + (New-IcingaPlugin 'count' $ServiceCount).MetricIndex('summary').MetricLabel('count') + ).Commit(); + + $CheckPackage.AddCheck($MetricPackage).Commit(); + return $CheckPackage.Compile(); } diff --git a/src/Plugins/Public/Invoke-IcingaCheckUptime.ps1 b/src/Plugins/Public/Invoke-IcingaCheckUptime.ps1 index 787c062..30acff7 100644 --- a/src/Plugins/Public/Invoke-IcingaCheckUptime.ps1 +++ b/src/Plugins/Public/Invoke-IcingaCheckUptime.ps1 @@ -29,9 +29,9 @@ Performance data uses the label 'windows::ifw_uptime::uptime' in seconds. | Critical | System.String | Critical threshold as duration or range, e.g. '30m:'. | | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|-----------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | +| Name | Type | Description | Default | +|-----------|--------------|------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -39,7 +39,7 @@ Performance data uses the label 'windows::ifw_uptime::uptime' in seconds. | NoPerfData | System.Management.Automation.SwitchParameter | Suppress the performance data output. | False | .OUTPUTS -System.Int32 — The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). +System.Int32 -- The Icinga plugin exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). .EXAMPLE PS> Invoke-IcingaCheckUptime -Warning '1d:' -Critical '30m:' @@ -66,16 +66,17 @@ function Invoke-IcingaCheckUptime() [switch]$NoPerfData = $false ); - [string]$CounterPath = '\System\System Up Time'; + [string]$CounterPath = '\System\System Up Time'; # Literal declaration, so the counter discovery at module start finds and warms it. New-IcingaPerformanceCounter -Counter @('\System\System Up Time'); - $CheckPackage = New-IcingaPlugin 'System Uptime'; - $CheckPackage.Verbose = $Verbosity; + $CheckPackage = New-IcingaPlugin 'System Uptime'; + $CheckPackage.Verbose = $Verbosity; + $CheckPackage.NoPerfData = $NoPerfData; - $Counters = Get-IcingaPerformanceCounter -Counter $CounterPath -StructureByInstance; - $Value = $null; + $Counters = Get-IcingaPerformanceCounter -Counter $CounterPath -StructureByInstance; + $Value = $null; if ($null -ne $Counters -and $null -ne $Counters['System']) { $Value = Get-IcingaPerformanceCounterValue -InputObject $Counters['System']['System Up Time']; @@ -88,23 +89,17 @@ function Invoke-IcingaCheckUptime() [uint64]$Uptime = [System.Math]::Round([double]$Value, 0); $CheckPackage.Name = [string]::Format('System Uptime: {0}', ('IcingaUnit' -as [type])::new([string]$Uptime, 's', '', $false).OutputString); - $UptimeCheck = New-IcingaPlugin 'System Uptime' $Uptime 's'; - $UptimeCheck.NoPerfData = $NoPerfData; - $CheckPackage.AddCheck( - $UptimeCheck. + (New-IcingaPlugin 'System Uptime' $Uptime 's'). MetricIndex('windows'). MetricLabel('uptime'). Warning($Warning). Critical($Critical). CheckRange() - ).Commit(); - - $BootCheck = New-IcingaPlugin 'Last Boot'; - $BootCheck.NoPerfData = $true; - - $CheckPackage.AddCheck( - $BootCheck.SetNotice([datetime]::Now.AddSeconds(-1 * [double]$Uptime).ToString('yyyy-MM-dd HH:mm:ss')) + ).AddCheck( + (New-IcingaPlugin 'Last Boot'). + SetNoPerfData($true). + SetNotice([datetime]::Now.AddSeconds(-1 * [double]$Uptime).ToString('yyyy-MM-dd HH:mm:ss')) ).Commit(); return $CheckPackage.Compile(); diff --git a/src/Provider/Disk/Public/Get-IcingaDiskInformation.ps1 b/src/Provider/Disk/Public/Get-IcingaDiskInformation.ps1 index 8caf3c9..37a5ecd 100644 --- a/src/Provider/Disk/Public/Get-IcingaDiskInformation.ps1 +++ b/src/Provider/Disk/Public/Get-IcingaDiskInformation.ps1 @@ -32,7 +32,7 @@ DiskInformationDiskQueryFailed), so the log shows where the collection stopped. | Entrypoint | System.String | View to return: 'PhysicalDisk', 'Partition' or 'Volume'. | PhysicalDisk | .OUTPUTS -System.Collections.Hashtable — The entries of the requested view, or an +System.Collections.Hashtable -- The entries of the requested view, or an IcingaError when its main class could not be read. Entry fields per view: Volume: DeviceId, Name, DriveLetter ('C:' or ''), Label, FileSystem, Size, @@ -77,7 +77,7 @@ function Get-IcingaDiskInformation() [string]$StorageNamespace = 'root/Microsoft/Windows/Storage'; - $Volumes = Get-IcingaWindowsInformation -ClassName 'Win32_Volume' -Filter 'DriveType = 3' -Property 'DeviceID', 'Name', 'DriveLetter', 'Label', 'FileSystem', 'Capacity', 'FreeSpace'; + $Volumes = Get-IcingaWindowsInformation -ClassName 'Win32_Volume' -Filter 'DriveType = 3' -Property 'DeviceID', 'Name', 'DriveLetter', 'Label', 'FileSystem', 'Capacity', 'FreeSpace'; if (Test-IcingaError -InputObject $Volumes) { if ($Entrypoint -eq 'Volume') { @@ -166,7 +166,7 @@ function Get-IcingaDiskInformation() continue; } - $LinkedVolume = $VolumeData[[string]$AccessPath]; + $LinkedVolume = $VolumeData[[string]$AccessPath]; $Entry.VolumeId = $LinkedVolume.DeviceId; $Entry.Volume = $LinkedVolume; diff --git a/src/Provider/FileSystem/Public/Get-IcingaDirectoryInformation.ps1 b/src/Provider/FileSystem/Public/Get-IcingaDirectoryInformation.ps1 index 7b50ef9..b5b9cef 100644 --- a/src/Provider/FileSystem/Public/Get-IcingaDirectoryInformation.ps1 +++ b/src/Provider/FileSystem/Public/Get-IcingaDirectoryInformation.ps1 @@ -34,34 +34,34 @@ with one check. A directory that cannot be read, including a subdirectory during a recursive scan, ends the scan with DirectoryAccessDenied or DirectoryReadFailed. .PARAMETER Path -| Name | Type | Description | Default | -|------|---------------|-----------------------------------------------|---------| -| Path | System.String | Directory to scan, e.g. 'C:\ProgramData\Logs'. | | +| Name | Type | Description | Default | +|------|---------------|------------------------------------------------|---------| +| Path | System.String | Directory to scan, e.g. 'C:\ProgramData\Logs'. | | .PARAMETER FileNames -| Name | Type | Description | Default | -|-----------|--------------|----------------------------------------------------------|---------| -| FileNames | System.Array | Wildcard patterns for the entry names, e.g. '*.log'. | @('*') | +| Name | Type | Description | Default | +|-----------|--------------|------------------------------------------------------|---------| +| FileNames | System.Array | Wildcard patterns for the entry names, e.g. '*.log'. | @('*') | .PARAMETER Recurse -| Name | Type | Description | Default | -|---------|----------------------------------------------|--------------------------------------|---------| -| Recurse | System.Management.Automation.SwitchParameter | Scan every subdirectory as well. | False | +| Name | Type | Description | Default | +|---------|----------------------------------------------|----------------------------------|---------| +| Recurse | System.Management.Automation.SwitchParameter | Scan every subdirectory as well. | False | .PARAMETER ChangeTimeEqual -| Name | Type | Description | Default | -|-----------------|---------------|---------------------------------------------------------------|---------| -| ChangeTimeEqual | System.String | Keep entries last written on the day this long ago, e.g. '1d'. | | +| Name | Type | Description | Default | +|-----------------|---------------|----------------------------------------------------------------|---------| +| ChangeTimeEqual | System.String | Keep entries last written on the day this long ago, e.g. '1d'. | | .PARAMETER ChangeYoungerThan -| Name | Type | Description | Default | -|-------------------|---------------|-----------------------------------------------------------|---------| -| ChangeYoungerThan | System.String | Keep entries last written within this duration, e.g. '5d'. | | +| Name | Type | Description | Default | +|-------------------|---------------|------------------------------------------------------------|---------| +| ChangeYoungerThan | System.String | Keep entries last written within this duration, e.g. '5d'. | | .PARAMETER ChangeOlderThan -| Name | Type | Description | Default | -|-----------------|---------------|----------------------------------------------------------------|---------| -| ChangeOlderThan | System.String | Keep entries last written longer ago than this, e.g. '10d'. | | +| Name | Type | Description | Default | +|-----------------|---------------|-------------------------------------------------------------|---------| +| ChangeOlderThan | System.String | Keep entries last written longer ago than this, e.g. '10d'. | | .PARAMETER CreationTimeEqual | Name | Type | Description | Default | @@ -69,47 +69,47 @@ a recursive scan, ends the scan with DirectoryAccessDenied or DirectoryReadFaile | CreationTimeEqual | System.String | Keep entries created on the day this long ago, e.g. '1d'. | | .PARAMETER CreationYoungerThan -| Name | Type | Description | Default | -|---------------------|---------------|------------------------------------------------------|---------| -| CreationYoungerThan | System.String | Keep entries created within this duration, e.g. '5d'. | | +| Name | Type | Description | Default | +|---------------------|---------------|-------------------------------------------------------|---------| +| CreationYoungerThan | System.String | Keep entries created within this duration, e.g. '5d'. | | .PARAMETER CreationOlderThan -| Name | Type | Description | Default | -|-------------------|---------------|----------------------------------------------------------|---------| -| CreationOlderThan | System.String | Keep entries created longer ago than this, e.g. '10d'. | | +| Name | Type | Description | Default | +|-------------------|---------------|--------------------------------------------------------|---------| +| CreationOlderThan | System.String | Keep entries created longer ago than this, e.g. '10d'. | | .PARAMETER AccessYoungerThan -| Name | Type | Description | Default | -|-------------------|---------------|------------------------------------------------------------|---------| -| AccessYoungerThan | System.String | Keep entries last accessed within this duration, e.g. '5d'. | | +| Name | Type | Description | Default | +|-------------------|---------------|-------------------------------------------------------------|---------| +| AccessYoungerThan | System.String | Keep entries last accessed within this duration, e.g. '5d'. | | .PARAMETER AccessOlderThan -| Name | Type | Description | Default | -|-----------------|---------------|---------------------------------------------------------------|---------| -| AccessOlderThan | System.String | Keep entries last accessed longer ago than this, e.g. '10d'. | | +| Name | Type | Description | Default | +|-----------------|---------------|--------------------------------------------------------------|---------| +| AccessOlderThan | System.String | Keep entries last accessed longer ago than this, e.g. '10d'. | | .PARAMETER FileSizeGreaterThan -| Name | Type | Description | Default | -|---------------------|---------------|-----------------------------------------------|---------| -| FileSizeGreaterThan | System.String | Keep files larger than this size, e.g. '20MB'. | | +| Name | Type | Description | Default | +|---------------------|---------------|------------------------------------------------|---------| +| FileSizeGreaterThan | System.String | Keep files larger than this size, e.g. '20MB'. | | .PARAMETER FileSizeSmallerThan -| Name | Type | Description | Default | -|---------------------|---------------|-----------------------------------------------|---------| -| FileSizeSmallerThan | System.String | Keep files smaller than this size, e.g. '5MB'. | | +| Name | Type | Description | Default | +|---------------------|---------------|------------------------------------------------|---------| +| FileSizeSmallerThan | System.String | Keep files smaller than this size, e.g. '5MB'. | | .PARAMETER IncludeFileList -| Name | Type | Description | Default | -|-----------------|----------------------------------------------|------------------------------------------------------|---------| -| IncludeFileList | System.Management.Automation.SwitchParameter | Also return every kept entry in FileList. | False | +| Name | Type | Description | Default | +|-----------------|----------------------------------------------|-------------------------------------------|---------| +| IncludeFileList | System.Management.Automation.SwitchParameter | Also return every kept entry in FileList. | False | .PARAMETER IgnoreMissingPath -| Name | Type | Description | Default | -|-------------------|----------------------------------------------|------------------------------------------------------------|---------| -| IgnoreMissingPath | System.Management.Automation.SwitchParameter | Return an empty result instead of an error for a missing path. | False | +| Name | Type | Description | Default | +|-------------------|----------------------------------------------|----------------------------------------------------------------|---------| +| IgnoreMissingPath | System.Management.Automation.SwitchParameter | Return an empty result instead of an error for a missing path. | False | .OUTPUTS -System.Collections.Hashtable — Path, Exists, FileCount, FolderCount, TotalCount, +System.Collections.Hashtable -- Path, Exists, FileCount, FolderCount, TotalCount, TotalSize, LargestFile, SmallestFile and AverageSize (sizes in bytes, the smallest file is 0 when no file was kept) and FileList (the kept System.IO.FileSystemInfo entries, empty unless IncludeFileList is set). Returns an IcingaError on failure. @@ -243,8 +243,8 @@ function Get-IcingaDirectoryInformation() [bool]$HasAccessFilter = ($null -ne $AccessAfter -or $null -ne $AccessBefore); [bool]$HasSizeFilter = ($null -ne $SizeAbove -or $null -ne $SizeBelow); - [bool]$MatchAll = ($FileNames.Count -eq 0); - [array]$Patterns = @(); + [bool]$MatchAll = ($FileNames.Count -eq 0); + [array]$Patterns = @(); foreach ($Name in $FileNames) { if ([string]$Name -eq '*') { @@ -273,7 +273,7 @@ function Get-IcingaDirectoryInformation() }; try { - $Root = [System.IO.DirectoryInfo]::new($Path); + $Root = [System.IO.DirectoryInfo]::new($Path); [bool]$RootExists = $Root.Exists; } catch { [hashtable]$ErrorData = @{ 'Path' = $Path; 'Error' = $_.Exception.Message; }; @@ -294,14 +294,14 @@ function Get-IcingaDirectoryInformation() [System.IO.FileAttributes]$SkipAttributes = [System.IO.FileAttributes]::Hidden -bor [System.IO.FileAttributes]::System; [System.IO.FileAttributes]$ReparsePoint = [System.IO.FileAttributes]::ReparsePoint; - $Pending = New-Object 'System.Collections.Generic.Stack[System.IO.DirectoryInfo]'; - $FileList = New-Object 'System.Collections.Generic.List[System.IO.FileSystemInfo]'; + $Pending = New-Object 'System.Collections.Generic.Stack[System.IO.DirectoryInfo]'; + $FileList = New-Object 'System.Collections.Generic.List[System.IO.FileSystemInfo]'; - [int]$FileCount = 0; - [int]$FolderCount = 0; - [long]$TotalSize = 0; - [long]$LargestFile = 0; - [long]$SmallestFile = -1; + [int]$FileCount = 0; + [int]$FolderCount = 0; + [long]$TotalSize = 0; + [long]$LargestFile = 0; + [long]$SmallestFile = -1; $Pending.Push($Root); diff --git a/src/Provider/Process/Public/Get-IcingaProcessInformation.ps1 b/src/Provider/Process/Public/Get-IcingaProcessInformation.ps1 index 3f66447..3491f13 100644 --- a/src/Provider/Process/Public/Get-IcingaProcessInformation.ps1 +++ b/src/Provider/Process/Public/Get-IcingaProcessInformation.ps1 @@ -39,7 +39,7 @@ PowerShell 5.1. | Exclude | System.Array | Skip processes matching these names (wildcards). | @() | .OUTPUTS -System.Collections.Hashtable — Keys Processes, MemoryTotal, CommitLimit and +System.Collections.Hashtable -- Keys Processes, MemoryTotal, CommitLimit and LogicalProcessors, or an IcingaError when the data could not be read. Processes is keyed by process name; every entry holds Name, Instances (keyed by process id, each with Id, Cpu, Memory, PageFile and Threads) and Total (Cpu, Memory, PageFile, @@ -127,7 +127,7 @@ function Get-IcingaProcessInformation() [uint64]$PageFile = 0; [int]$Threads = 0; - $Value = Get-IcingaPerformanceCounterValue -InputObject $Values['% Processor Time']; + $Value = Get-IcingaPerformanceCounterValue -InputObject $Values['% Processor Time']; if ($null -ne $Value -and $Value -isnot [string]) { $Cpu = [double]$Value / $Processors; } diff --git a/src/Provider/ScheduledTask/Public/Get-IcingaScheduledTask.ps1 b/src/Provider/ScheduledTask/Public/Get-IcingaScheduledTask.ps1 new file mode 100644 index 0000000..9307cce --- /dev/null +++ b/src/Provider/ScheduledTask/Public/Get-IcingaScheduledTask.ps1 @@ -0,0 +1,188 @@ +<# +.SYNOPSIS +Collect Windows scheduled tasks and their runtime metadata + +.DESCRIPTION +Get-IcingaScheduledTask is the data source for Invoke-IcingaCheckScheduledTask. +It queries all scheduled tasks via Get-ScheduledTask, filters them by TaskPath, +ExcludeTaskPath, TaskName and ExcludeTaskName (wildcards supported), and enriches +each matching task with runtime information from Get-ScheduledTaskInfo (last run +time, next run time, last task result and number of missed runs). + +Run timestamps are returned both as formatted invariant strings +('yyyy/MM/dd HH:mm:ss', or '' when never run / not scheduled) and as offsets in +seconds relative to the current time (LastRunOffset counts up from the last run, +NextRunOffset counts down to the next scheduled run, 0 when unset). Tasks are +grouped by TaskPath and sorted by TaskName. + +.PARAMETER TaskName +| Name | Type | Description | Default | +|----------|--------------|--------------------------------------------------------------|---------| +| TaskName | System.Array | Only collect tasks matching these names (wildcards allowed). | @() | + +.PARAMETER ExcludeTaskName +| Name | Type | Description | Default | +|-----------------|--------------|--------------------------------------------------------------|---------| +| ExcludeTaskName | System.Array | Skip tasks matching these names (wildcards allowed). | @() | + +.PARAMETER TaskPath +| Name | Type | Description | Default | +|----------|--------------|--------------------------------------------------------------|---------| +| TaskPath | System.Array | Only collect tasks matching these paths (wildcards allowed). | @() | + +.PARAMETER ExcludeTaskPath +| Name | Type | Description | Default | +|-----------------|--------------|--------------------------------------------------------------|---------| +| ExcludeTaskPath | System.Array | Skip tasks matching these paths (wildcards allowed). | @() | + +.OUTPUTS +System.Collections.Hashtable -- Hashtable with keys Tasks (hashtable keyed by +TaskPath containing arrays of task hashtables) and TaskNames (array of known task +names after path and exclude filtering), or an IcingaError when querying failed. + +.EXAMPLE +PS> Get-IcingaScheduledTask -TaskPath '\Icinga\*' + +Returns all scheduled tasks under the \Icinga\ task path hierarchy. + +.NOTES +Windows-only. Relies on Get-ScheduledTask and Get-ScheduledTaskInfo from the +ScheduledTasks module. +#> +function Get-IcingaScheduledTask() +{ + param ( + [array]$TaskName = @(), + [array]$ExcludeTaskName = @(), + [array]$TaskPath = @(), + [array]$ExcludeTaskPath = @() + ); + + if ($null -eq (Get-Command -Name 'Get-ScheduledTask' -ErrorAction SilentlyContinue)) { + [hashtable]$ErrorData = @{ 'Command' = 'Get-ScheduledTask'; }; + return (Write-FunctionReturnValue -ReturnValue 'ScheduledTaskQueryFailed' -Data $ErrorData -OverrideReturn (('IcingaError' -as [type])::new('ScheduledTaskQueryFailed', 'The ScheduledTasks cmdlet Get-ScheduledTask is not available on this system', $ErrorData))); + } + + [array]$RawTasks = @(); + + try { + $RawTasks = @(Get-ScheduledTask -TaskName '*' -ErrorAction Stop); + } catch { + [string]$ErrorMessage = $_.Exception.Message; + [hashtable]$ErrorData = @{ 'Error' = $ErrorMessage; }; + return (Write-FunctionReturnValue -ReturnValue 'ScheduledTaskQueryFailed' -Data $ErrorData -OverrideReturn (('IcingaError' -as [type])::new('ScheduledTaskQueryFailed', ('Failed to query scheduled tasks: {0}' -f $ErrorMessage), $ErrorData))); + } + + [hashtable]$GroupedTasks = @{ }; + [hashtable]$KnownNames = @{ }; + $StatusMap = 'IcingaScheduledTaskStatusMap' -as [type]; + [datetime]$Now = [datetime]::Now; + + foreach ($Task in (ConvertTo-IcingaSortedArray -InputObject $RawTasks -Property 'TaskName')) { + if ($null -eq $Task) { + continue; + } + + [string]$Name = [string]$Task.TaskName; + [string]$Path = [string]$Task.TaskPath; + + if ([string]::IsNullOrEmpty($Name) -or [string]::IsNullOrEmpty($Path)) { + continue; + } + + if ((Test-IcingaArrayFilter -InputObject $Path -Include $TaskPath -Exclude $ExcludeTaskPath) -eq $false) { + continue; + } + + if ((Test-IcingaArrayFilter -InputObject $Name -Exclude $ExcludeTaskName) -eq $false) { + continue; + } + + $KnownNames[$Name] = $true; + + if ((Test-IcingaArrayFilter -InputObject $Name -Include $TaskName) -eq $false) { + continue; + } + + $TaskInfo = $null; + try { + $TaskInfo = Get-ScheduledTaskInfo -TaskName $Name -TaskPath $Path -ErrorAction SilentlyContinue; + } catch { + $TaskInfo = $null; + } + + [string]$LastRunTime = ''; + [double]$LastRunOffset = 0; + [string]$NextRunTime = ''; + [double]$NextRunOffset = 0; + [int]$MissedRuns = 0; + [int64]$LastTaskResult = 0; + + if ($null -ne $TaskInfo) { + if ($null -ne $TaskInfo.NumberOfMissedRuns) { + $MissedRuns = [int]$TaskInfo.NumberOfMissedRuns; + } + + if ($null -ne $TaskInfo.LastTaskResult) { + $LastTaskResult = [int64]$TaskInfo.LastTaskResult; + } + + if ($null -ne $TaskInfo.LastRunTime) { + [datetime]$ParsedLast = [datetime]::MinValue; + if ($TaskInfo.LastRunTime -is [datetime]) { + $ParsedLast = [datetime]$TaskInfo.LastRunTime; + } else { + [void][datetime]::TryParse([string]$TaskInfo.LastRunTime, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$ParsedLast); + } + + # Windows Task Scheduler reports 1999-11-30 00:00:00 with result 267011 + # (SCHED_S_TASK_HAS_NOT_RUN) when a task has never been executed. + [bool]$NeverRunSentinel = ($ParsedLast.Year -eq 1999 -and $ParsedLast.Month -eq 11 -and $ParsedLast.Day -eq 30 -and $LastTaskResult -eq 267011); + + if ($ParsedLast.Year -gt 1970 -and -not $NeverRunSentinel) { + $LastRunTime = $ParsedLast.ToString('yyyy/MM/dd HH:mm:ss', [System.Globalization.CultureInfo]::InvariantCulture); + $LastRunOffset = [System.Math]::Round(($Now - $ParsedLast).TotalSeconds, 0); + } + } + + if ($null -ne $TaskInfo.NextRunTime) { + [datetime]$ParsedNext = [datetime]::MinValue; + if ($TaskInfo.NextRunTime -is [datetime]) { + $ParsedNext = [datetime]$TaskInfo.NextRunTime; + } else { + [void][datetime]::TryParse([string]$TaskInfo.NextRunTime, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$ParsedNext); + } + + if ($ParsedNext.Year -gt 1970) { + $NextRunTime = $ParsedNext.ToString('yyyy/MM/dd HH:mm:ss', [System.Globalization.CultureInfo]::InvariantCulture); + $NextRunOffset = [System.Math]::Round(($ParsedNext - $Now).TotalSeconds, 0); + } + } + } + + [hashtable]$TaskEntry = @{ + 'TaskName' = $Name; + 'TaskPath' = $Path; + 'State' = $StatusMap::Resolve($Task.State); + 'LastRunTime' = $LastRunTime; + 'LastRunOffset' = $LastRunOffset; + 'NextRunTime' = $NextRunTime; + 'NextRunOffset' = $NextRunOffset; + 'MissedRuns' = $MissedRuns; + 'LastTaskResult' = $LastTaskResult; + }; + + if ($GroupedTasks.ContainsKey($Path) -eq $false) { + $GroupedTasks[$Path] = @($TaskEntry); + } else { + $GroupedTasks[$Path] += $TaskEntry; + } + } + + [hashtable]$Result = @{ + 'Tasks' = $GroupedTasks; + 'TaskNames' = @($KnownNames.Keys); + }; + + return (Write-FunctionReturnValue -ReturnValue 'ScheduledTaskInformationCollected' -Data @{ 'Count' = $GroupedTasks.Count; } -OverrideReturn $Result); +} diff --git a/src/Tools/Private/Test-ModuleWildcardMatch.ps1 b/src/Tools/Private/Test-ModuleWildcardMatch.ps1 index 2d688e6..7d81845 100644 --- a/src/Tools/Private/Test-ModuleWildcardMatch.ps1 +++ b/src/Tools/Private/Test-ModuleWildcardMatch.ps1 @@ -19,7 +19,7 @@ a broken filter argument never aborts a plugin. | Pattern | System.String | Wildcard pattern to match. | | .OUTPUTS -System.Boolean — True when the value matches the pattern. +System.Boolean -- True when the value matches the pattern. .EXAMPLE PS> Test-ModuleWildcardMatch -Value 'Spooler' -Pattern 'spo*' diff --git a/src/Tools/Public/ConvertTo-IcingaSortedArray.ps1 b/src/Tools/Public/ConvertTo-IcingaSortedArray.ps1 index 66f0646..8d350bf 100644 --- a/src/Tools/Public/ConvertTo-IcingaSortedArray.ps1 +++ b/src/Tools/Public/ConvertTo-IcingaSortedArray.ps1 @@ -23,17 +23,17 @@ member name. | InputObject | System.Array | The elements to sort. | @() | .PARAMETER Property -| Name | Type | Description | Default | -|----------|--------------|-------------------------------------------------------------|---------| -| Property | System.Array | Properties to sort by, in order of precedence; empty sorts the elements. | @() | +| Name | Type | Description | Default | +|----------|--------------|--------------------------------------------------------------------------|---------| +| Property | System.Array | Properties to sort by, in order of precedence; empty sorts the elements. | @() | .PARAMETER Descending -| Name | Type | Description | Default | -|------------|----------------------------------------------|-------------------------------|---------| -| Descending | System.Management.Automation.SwitchParameter | Sort in descending order. | False | +| Name | Type | Description | Default | +|------------|----------------------------------------------|---------------------------|---------| +| Descending | System.Management.Automation.SwitchParameter | Sort in descending order. | False | .OUTPUTS -System.Object[] — A new array with the sorted elements; the input stays unchanged. +System.Object[] -- A new array with the sorted elements; the input stays unchanged. .EXAMPLE PS> ConvertTo-IcingaSortedArray -InputObject @('0,10', '_Total', '0,2', '0,_Total') diff --git a/src/Tools/Public/Get-IcingaWindowsInformation.ps1 b/src/Tools/Public/Get-IcingaWindowsInformation.ps1 index fa33c35..5ca9ca4 100644 --- a/src/Tools/Public/Get-IcingaWindowsInformation.ps1 +++ b/src/Tools/Public/Get-IcingaWindowsInformation.ps1 @@ -33,9 +33,9 @@ the ReturnCode of the IcingaError. | Namespace | System.String | CIM namespace of the class. | root/cimv2 | .PARAMETER Filter -| Name | Type | Description | Default | -|--------|---------------|----------------------------------------------|---------| -| Filter | System.String | WQL filter, e.g. 'DriveType = 3'; '' for all. | | +| Name | Type | Description | Default | +|--------|---------------|-----------------------------------------------|---------| +| Filter | System.String | WQL filter, e.g. 'DriveType = 3'; '' for all. | | .PARAMETER Property | Name | Type | Description | Default | @@ -43,7 +43,7 @@ the ReturnCode of the IcingaError. | Property | System.Array | Properties to fetch; empty fetches all of them. | @() | .OUTPUTS -System.Object[] — The CIM instances on success (an empty array when nothing +System.Object[] -- The CIM instances on success (an empty array when nothing matches), or an IcingaError when the query failed. .EXAMPLE @@ -102,8 +102,8 @@ function Get-IcingaWindowsInformation() 'InvalidParameter' = 'WindowsInformationInvalidQuery'; }; - [string]$NativeErrorCode = [string]$_.Exception.NativeErrorCode; - [string]$ReturnCode = 'WindowsInformationQueryFailed'; + [string]$NativeErrorCode = [string]$_.Exception.NativeErrorCode; + [string]$ReturnCode = 'WindowsInformationQueryFailed'; if ($NativeErrorCodes.ContainsKey($NativeErrorCode)) { $ReturnCode = $NativeErrorCodes[$NativeErrorCode]; diff --git a/src/Tools/Public/Test-IcingaArrayFilter.ps1 b/src/Tools/Public/Test-IcingaArrayFilter.ps1 index 67a52c1..ed4f8ab 100644 --- a/src/Tools/Public/Test-IcingaArrayFilter.ps1 +++ b/src/Tools/Public/Test-IcingaArrayFilter.ps1 @@ -32,8 +32,8 @@ pattern. | Exclude | System.Array | Wildcard patterns of which none may match. | @() | .OUTPUTS -System.Boolean — For a single value, whether it passes the filters. -System.Object[] — For an array, the elements that pass the filters. +System.Boolean -- For a single value, whether it passes the filters. +System.Object[] -- For an array, the elements that pass the filters. .EXAMPLE PS> Test-IcingaArrayFilter -InputObject 'Spooler' -Include 'Spo*' -Exclude 'WinRM' @@ -53,9 +53,9 @@ plugins stay usable in JEA sessions. function Test-IcingaArrayFilter() { param ( - $InputObject = $null, - [array]$Include = @(), - [array]$Exclude = @() + [object]$InputObject = $null, + [array]$Include = @(), + [array]$Exclude = @() ); if ($InputObject -is [array]) { From 8515dd10d88be145f64a7f88f247746679406fb6 Mon Sep 17 00:00:00 2001 From: Lord Hepipud Date: Fri, 13 Nov 2026 13:26:02 +0100 Subject: [PATCH 4/6] Restructure Plugins layout, restore provider exit codes and update docs - Reorganize src/Plugins/ into Checks/Public, Lib/Private and Provider//Private (removing top-level src/Provider/) so all plugin components live under one domain folder consistent with src/Core/ - Move New-IcingaPlugin and all Get-Icinga* providers from Public/ to Private/ so only executable Invoke-IcingaCheck* cmdlets are exported into the user session and internal helpers/providers are comment-stripped in the compiled kernel - Restore Disk (4300-4350), Directory (4400-4450) and Process (4500-4550) provider return-code entries in Set-InternalExitCodes alongside ScheduledTask (4600-4650) - Move Pester test helpers into BeforeAll in Get-IcingaScheduledTask.Tests.ps1 and Invoke-IcingaCheckScheduledTask.Tests.ps1 for Pester 5 Run-phase scope, and run New-IcingaPlugin.Tests.ps1 calls in module scope - Update plugin developer guides with the new src/Plugins/ paths and regenerate API reference documentation --- Tests/Get-IcingaScheduledTask.Tests.ps1 | 90 +- .../Invoke-IcingaCheckScheduledTask.Tests.ps1 | 96 +- Tests/New-IcingaPlugin.Tests.ps1 | 25 +- .../Plugins/02-IcingaPlugin-Reference.md | 4 +- .../Plugins/03-Result-and-Error-Objects.md | 6 +- .../04-Custom-Plugin-Developer-Guide.md | 23 +- docs/Icinga.Core.ErrorHandling.md | 2 +- docs/Icinga.Plugins.Checks.md | 1279 +++++++++++++++++ ...cinga.Plugins.md => Icinga.Plugins.Lib.md} | 10 +- docs/Icinga.Plugins.Provider.Disk.md | 94 ++ docs/Icinga.Plugins.Provider.FileSystem.md | 169 +++ docs/Icinga.Plugins.Provider.Process.md | 82 ++ docs/Icinga.Plugins.Provider.ScheduledTask.md | 77 + docs/Icinga.Tools.md | 1141 +++++++++------ docs/index.md | 19 +- .../Private/Set-InternalExitCodes.ps1 | 72 + .../Public/Invoke-IcingaCheckCPU.ps1 | 0 .../Public/Invoke-IcingaCheckDirectory.ps1 | 0 .../Public/Invoke-IcingaCheckMemory.ps1 | 0 .../Invoke-IcingaCheckPartitionSpace.ps1 | 0 .../Public/Invoke-IcingaCheckPerfCounter.ps1 | 0 .../Public/Invoke-IcingaCheckProcess.ps1 | 0 .../Invoke-IcingaCheckScheduledTask.ps1 | 0 .../Public/Invoke-IcingaCheckService.ps1 | 0 .../Public/Invoke-IcingaCheckUptime.ps1 | 0 .../Private}/New-IcingaPlugin.ps1 | 0 .../Private}/Get-IcingaDiskInformation.ps1 | 0 .../Get-IcingaDirectoryInformation.ps1 | 0 .../Private}/Get-IcingaProcessInformation.ps1 | 0 .../Private}/Get-IcingaScheduledTask.ps1 | 0 30 files changed, 2627 insertions(+), 562 deletions(-) create mode 100644 docs/Icinga.Plugins.Checks.md rename docs/{Icinga.Plugins.md => Icinga.Plugins.Lib.md} (90%) create mode 100644 docs/Icinga.Plugins.Provider.Disk.md create mode 100644 docs/Icinga.Plugins.Provider.FileSystem.md create mode 100644 docs/Icinga.Plugins.Provider.Process.md create mode 100644 docs/Icinga.Plugins.Provider.ScheduledTask.md rename src/Plugins/{ => Checks}/Public/Invoke-IcingaCheckCPU.ps1 (100%) rename src/Plugins/{ => Checks}/Public/Invoke-IcingaCheckDirectory.ps1 (100%) rename src/Plugins/{ => Checks}/Public/Invoke-IcingaCheckMemory.ps1 (100%) rename src/Plugins/{ => Checks}/Public/Invoke-IcingaCheckPartitionSpace.ps1 (100%) rename src/Plugins/{ => Checks}/Public/Invoke-IcingaCheckPerfCounter.ps1 (100%) rename src/Plugins/{ => Checks}/Public/Invoke-IcingaCheckProcess.ps1 (100%) rename src/Plugins/{ => Checks}/Public/Invoke-IcingaCheckScheduledTask.ps1 (100%) rename src/Plugins/{ => Checks}/Public/Invoke-IcingaCheckService.ps1 (100%) rename src/Plugins/{ => Checks}/Public/Invoke-IcingaCheckUptime.ps1 (100%) rename src/Plugins/{Public => Lib/Private}/New-IcingaPlugin.ps1 (100%) rename src/{Provider/Disk/Public => Plugins/Provider/Disk/Private}/Get-IcingaDiskInformation.ps1 (100%) rename src/{Provider/FileSystem/Public => Plugins/Provider/FileSystem/Private}/Get-IcingaDirectoryInformation.ps1 (100%) rename src/{Provider/Process/Public => Plugins/Provider/Process/Private}/Get-IcingaProcessInformation.ps1 (100%) rename src/{Provider/ScheduledTask/Public => Plugins/Provider/ScheduledTask/Private}/Get-IcingaScheduledTask.ps1 (100%) diff --git a/Tests/Get-IcingaScheduledTask.Tests.ps1 b/Tests/Get-IcingaScheduledTask.Tests.ps1 index 4dbc3c5..f0cae5d 100644 --- a/Tests/Get-IcingaScheduledTask.Tests.ps1 +++ b/Tests/Get-IcingaScheduledTask.Tests.ps1 @@ -3,57 +3,57 @@ if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; } -function Invoke-TestGetScheduledTask() -{ - param ( - [array]$Tasks = @(), - [hashtable]$Infos = @{ }, - [hashtable]$Arguments = @{ }, - [switch]$Fail = $false - ); - - return (& $script:IcingaModule { - param ($Tasks, $Infos, $Arguments, $Fail); - - function Get-ScheduledTask() - { - param ( - [string]$TaskName = '*', - [string]$ErrorAction = 'Continue' - ); - - if ($Fail) { - throw 'Access is denied'; - } - - return $Tasks; - } +Describe 'Get-IcingaScheduledTask' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; - function Get-ScheduledTaskInfo() + function Invoke-TestGetScheduledTask() { param ( - [string]$TaskName = '', - [string]$TaskPath = '', - [string]$ErrorAction = 'Continue' + [array]$Tasks = @(), + [hashtable]$Infos = @{ }, + [hashtable]$Arguments = @{ }, + [switch]$Fail = $false ); - [string]$Key = '{0}{1}' -f $TaskPath, $TaskName; - if ($Infos.ContainsKey($Key)) { - return $Infos[$Key]; - } - - return $null; + return (& $script:IcingaModule { + param ($Tasks, $Infos, $Arguments, $Fail); + + function Get-ScheduledTask() + { + param ( + [string]$TaskName = '*', + [string]$ErrorAction = 'Continue' + ); + + if ($Fail) { + throw 'Access is denied'; + } + + return $Tasks; + } + + function Get-ScheduledTaskInfo() + { + param ( + [string]$TaskName = '', + [string]$TaskPath = '', + [string]$ErrorAction = 'Continue' + ); + + [string]$Key = '{0}{1}' -f $TaskPath, $TaskName; + if ($Infos.ContainsKey($Key)) { + return $Infos[$Key]; + } + + return $null; + } + + return (Get-IcingaScheduledTask @Arguments); + } $Tasks $Infos $Arguments $Fail); } - - return (Get-IcingaScheduledTask @Arguments); - } $Tasks $Infos $Arguments $Fail); -} - -Describe 'Get-IcingaScheduledTask' { - BeforeAll { - $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | - Where-Object { $_.ModuleType -eq 'Script' } | - Select-Object -First 1; } Context 'Task collection and filtering' { diff --git a/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 b/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 index 8314fee..7fb87c1 100644 --- a/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 @@ -3,52 +3,6 @@ if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; } -function Invoke-TestScheduledTaskCheck() -{ - param ( - [array]$Tasks = @(), - [hashtable]$Infos = @{ }, - [hashtable]$Arguments = @{ }, - [switch]$Fail = $false - ); - - return (& $script:IcingaModule { - param ($Tasks, $Infos, $Arguments, $Fail); - - function Get-ScheduledTask() - { - param ( - [string]$TaskName = '*', - [string]$ErrorAction = 'Continue' - ); - - if ($Fail) { - throw 'Access is denied'; - } - - return $Tasks; - } - - function Get-ScheduledTaskInfo() - { - param ( - [string]$TaskName = '', - [string]$TaskPath = '', - [string]$ErrorAction = 'Continue' - ); - - [string]$Key = '{0}{1}' -f $TaskPath, $TaskName; - if ($Infos.ContainsKey($Key)) { - return $Infos[$Key]; - } - - return $null; - } - - return (Invoke-IcingaCheckScheduledTask @Arguments); - } $Tasks $Infos $Arguments $Fail); -} - Describe 'Invoke-IcingaCheckScheduledTask' { BeforeAll { $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | @@ -57,12 +11,58 @@ Describe 'Invoke-IcingaCheckScheduledTask' { $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; - $script:DefaultTask = [PSCustomObject]@{ + function Invoke-TestScheduledTaskCheck() + { + param ( + [array]$Tasks = @(), + [hashtable]$Infos = @{ }, + [hashtable]$Arguments = @{ }, + [switch]$Fail = $false + ); + + return (& $script:IcingaModule { + param ($Tasks, $Infos, $Arguments, $Fail); + + function Get-ScheduledTask() + { + param ( + [string]$TaskName = '*', + [string]$ErrorAction = 'Continue' + ); + + if ($Fail) { + throw 'Access is denied'; + } + + return $Tasks; + } + + function Get-ScheduledTaskInfo() + { + param ( + [string]$TaskName = '', + [string]$TaskPath = '', + [string]$ErrorAction = 'Continue' + ); + + [string]$Key = '{0}{1}' -f $TaskPath, $TaskName; + if ($Infos.ContainsKey($Key)) { + return $Infos[$Key]; + } + + return $null; + } + + return (Invoke-IcingaCheckScheduledTask @Arguments); + } $Tasks $Infos $Arguments $Fail); + } + + $script:DefaultTask = [PSCustomObject]@{ 'TaskName' = 'Renew Certificate'; 'TaskPath' = '\Icinga\Icinga for Windows\'; 'State' = 'Ready'; }; - $script:DefaultInfo = @{ + $script:DefaultInfo = @{ '\Icinga\Icinga for Windows\Renew Certificate' = [PSCustomObject]@{ 'LastRunTime' = [datetime]::Now.AddHours(-1); 'NextRunTime' = [datetime]::Now.AddHours(2); diff --git a/Tests/New-IcingaPlugin.Tests.ps1 b/Tests/New-IcingaPlugin.Tests.ps1 index 5dffde2..fa46220 100644 --- a/Tests/New-IcingaPlugin.Tests.ps1 +++ b/Tests/New-IcingaPlugin.Tests.ps1 @@ -12,6 +12,13 @@ Describe 'New-IcingaPlugin' { # Daemon mode keeps Compile from writing to the console; the result is still # stored in Private.Icinga.CheckResult. $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + function Invoke-TestNewPlugin() + { + return (& $script:IcingaModule { + New-IcingaPlugin @args; + } @args); + } } AfterAll { @@ -24,13 +31,13 @@ Describe 'New-IcingaPlugin' { It 'creates an instance of the IcingaPlugin type loaded by the current runspace' { $PluginType = & $script:IcingaModule { 'IcingaPlugin' -as [type] }; - $Plugin = New-IcingaPlugin 'Disks'; + $Plugin = Invoke-TestNewPlugin 'Disks'; ($Plugin.GetType() -eq $PluginType) | Should -BeTrue; } It 'creates a container from a name only' { - $Plugin = New-IcingaPlugin -Name 'Disks'; + $Plugin = & $script:IcingaModule { New-IcingaPlugin -Name 'Disks' }; $Plugin.Name | Should -Be 'Disks'; $Plugin.Value | Should -BeNullOrEmpty; @@ -38,21 +45,21 @@ Describe 'New-IcingaPlugin' { } It 'creates a check from a name and a value' { - $Plugin = New-IcingaPlugin -Name 'Load' -Value 95; + $Plugin = & $script:IcingaModule { New-IcingaPlugin -Name 'Load' -Value 95 }; $Plugin.Value | Should -Be 95; $Plugin.Unit | Should -Be ''; } It 'passes the unit to the check' { - $Plugin = New-IcingaPlugin -Name 'Load' -Value 95 -Unit '%'; + $Plugin = & $script:IcingaModule { New-IcingaPlugin -Name 'Load' -Value 95 -Unit '%' }; $Plugin.Value | Should -Be 95; $Plugin.Unit | Should -Be '%'; } It 'binds name, value and unit by position' { - $Plugin = New-IcingaPlugin 'C:' 55 '%'; + $Plugin = Invoke-TestNewPlugin 'C:' 55 '%'; $Plugin.Name | Should -Be 'C:'; $Plugin.Value | Should -Be 55; @@ -60,16 +67,16 @@ Describe 'New-IcingaPlugin' { } It 'returns a node whose fluent chain evaluates and compiles the check' { - $ExitCode = (New-IcingaPlugin 'Load' 95 '%').Warning('80').Critical('90').CheckRange().Compile(); + $ExitCode = (Invoke-TestNewPlugin 'Load' 95 '%').Warning('80').Critical('90').CheckRange().Compile(); $ExitCode | Should -Be 2; $Global:IcingaForWindows.Private.Icinga.CheckResult.ToString() | Should -Match '^\[CRITICAL\] Load'; } It 'aggregates the checks added to a container' { - $CheckPackage = New-IcingaPlugin 'Disks'; - $CheckPackage.AddCheck((New-IcingaPlugin 'C:' 55 '%').Warning('80').CheckRange()).Commit(); - $CheckPackage.AddCheck((New-IcingaPlugin 'D:' 85 '%').Warning('80').CheckRange()).Commit(); + $CheckPackage = Invoke-TestNewPlugin 'Disks'; + $CheckPackage.AddCheck((Invoke-TestNewPlugin 'C:' 55 '%').Warning('80').CheckRange()).Commit(); + $CheckPackage.AddCheck((Invoke-TestNewPlugin 'D:' 85 '%').Warning('80').CheckRange()).Commit(); $CheckPackage.Compile() | Should -Be 1; } diff --git a/docs/Developer/Plugins/02-IcingaPlugin-Reference.md b/docs/Developer/Plugins/02-IcingaPlugin-Reference.md index 83ae7f6..7b461f7 100644 --- a/docs/Developer/Plugins/02-IcingaPlugin-Reference.md +++ b/docs/Developer/Plugins/02-IcingaPlugin-Reference.md @@ -11,7 +11,7 @@ This document is the complete technical reference for **[`New-IcingaPlugin`](#1- ## 1. `New-IcingaPlugin` Factory Cmdlet -`New-IcingaPlugin` is the runspace-safe factory function that every plugin and helper function outside `src/Classes` must use instead of `[IcingaPlugin]::new()`. It resolves the `IcingaPlugin` class in the calling runspace (`'IcingaPlugin' -as [type]`) and invokes either `$PluginType::new($Name)` (when neither `-Value` nor `-Unit` is bound) or `$PluginType::new($Name, $Value, $Unit)`. +Defined in [`src/Plugins/Lib/Private/New-IcingaPlugin.ps1`](../../../src/Plugins/Lib/Private/New-IcingaPlugin.ps1), `New-IcingaPlugin` is the runspace-safe factory function that every plugin and helper function outside `src/Classes` must use instead of `[IcingaPlugin]::new()`. It resolves the `IcingaPlugin` class in the calling runspace (`'IcingaPlugin' -as [type]`) and invokes either `$PluginType::new($Name)` (when neither `-Value` nor `-Unit` is bound) or `$PluginType::new($Name, $Value, $Unit)`. ### Syntax @@ -52,6 +52,8 @@ $CheckPackage.AddCheck( ## 2. `IcingaPlugin` Class Properties +The `IcingaPlugin` class is defined in [`src/Classes/Icinga/IcingaPlugin.ps1`](../../../src/Classes/Icinga/IcingaPlugin.ps1). + ### Public Instance Properties (10) These properties form the public state surface of an `IcingaPlugin` node. Each boolean/integer flag also has a corresponding fluent `Set*` method for method chaining. diff --git a/docs/Developer/Plugins/03-Result-and-Error-Objects.md b/docs/Developer/Plugins/03-Result-and-Error-Objects.md index e6d5b39..3c30d12 100644 --- a/docs/Developer/Plugins/03-Result-and-Error-Objects.md +++ b/docs/Developer/Plugins/03-Result-and-Error-Objects.md @@ -14,7 +14,7 @@ Alongside [`IcingaPlugin`](02-IcingaPlugin-Reference.md), two lightweight compan ## 1. `IcingaCheckResult` Class -When `IcingaPlugin.Compile()` finishes evaluating a plugin tree, it stores an `IcingaCheckResult` instance in the current runspace's private runtime state: +Defined in [`src/Classes/Icinga/IcingaCheckResult.ps1`](../../../src/Classes/Icinga/IcingaCheckResult.ps1). When `IcingaPlugin.Compile()` finishes evaluating a plugin tree, it stores an `IcingaCheckResult` instance in the current runspace's private runtime state: ```powershell $Global:IcingaForWindows.Private.Icinga.CheckResult @@ -62,7 +62,7 @@ $Result.PerformanceData # e.g. @('icingaicingaforwindowsrenewcertificate::ifw_sc ## 2. `IcingaError` Class -Data collection functions (such as `Get-IcingaWindowsInformation` or provider functions like `Get-IcingaScheduledTask`) must **never** throw unhandled exceptions into a plugin. Instead, when an underlying query (CIM/WMI, Task Scheduler, Registry, Service Controller) fails, the provider returns an `IcingaError` object describing the failure. +Defined in [`src/Classes/Icinga/IcingaError.ps1`](../../../src/Classes/Icinga/IcingaError.ps1). Data collection functions (such as `Get-IcingaWindowsInformation` or provider functions like `Get-IcingaScheduledTask`) must **never** throw unhandled exceptions into a plugin. Instead, when an underlying query (CIM/WMI, Task Scheduler, Registry, Service Controller) fails, the provider returns an `IcingaError` object describing the failure. ### Properties @@ -111,7 +111,7 @@ try { ## 3. `Test-IcingaError` Cmdlet -`Test-IcingaError` is the runspace-safe cmdlet used by plugins and providers to check whether a data collection call returned an `IcingaError`. +Defined in [`src/Core/ErrorHandling/Public/Test-IcingaError.ps1`](../../../src/Core/ErrorHandling/Public/Test-IcingaError.ps1), `Test-IcingaError` is the runspace-safe cmdlet used by plugins and providers to check whether a data collection call returned an `IcingaError`. ### Syntax diff --git a/docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md b/docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md index 7ad1793..35c9a78 100644 --- a/docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md +++ b/docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md @@ -21,23 +21,28 @@ By the end of this tutorial, you will have built a realistic **Print Spooler Que ## 1. Repository Layout and Separation of Concerns -In Icinga for Windows, every check is split into two layers: +In Icinga for Windows, the plugin subsystem under `src/Plugins/` is organized into three areas: -* **Provider (`src/Provider//Public/Get-Icinga.ps1`)**: Queries the operating system (CIM/WMI, Performance Counters, Services, Task Scheduler, Registry), filters the raw objects, and returns either a clean collection/hashtable of data objects or an [`IcingaError`](03-Result-and-Error-Objects.md#2-icingaerror-class) when collection fails. -* **Plugin (`src/Plugins/Public/Invoke-IcingaCheck.ps1`)**: Accepts user threshold parameters (`-Warning`, `-Critical`, `-State`, `-NoPerfData`, `-Verbosity`), calls the provider, builds the `IcingaPlugin` check tree with `New-IcingaPlugin`, and returns `$CheckPackage.Compile()`. +* **Plugin Library (`src/Plugins/Lib/Private/`)**: Internal plugin helper functions such as [`New-IcingaPlugin`](02-IcingaPlugin-Reference.md#1-new-icingaplugin-factory-cmdlet) for creating runspace-safe `IcingaPlugin` nodes. +* **Provider (`src/Plugins/Provider//Private/Get-Icinga.ps1`)**: Queries the operating system (CIM/WMI, Performance Counters, Services, Task Scheduler, Registry), filters the raw objects, and returns either a clean collection/hashtable of data objects or an [`IcingaError`](03-Result-and-Error-Objects.md#2-icingaerror-class) when collection fails. +* **Plugin (`src/Plugins/Checks/Public/Invoke-IcingaCheck.ps1`)**: Accepts user threshold parameters (`-Warning`, `-Critical`, `-State`, `-NoPerfData`, `-Verbosity`), calls the provider, builds the `IcingaPlugin` check tree with `New-IcingaPlugin`, and returns `$CheckPackage.Compile()`. ```text src |_ Classes | |_ DataTypes | |_ IcingaSpoolerState.ps1 # Optional enum for status codes - |_ Provider - | |_ Spooler - | |_ Public - | |_ Get-IcingaSpoolerQueue.ps1 |_ Plugins - |_ Public - |_ Invoke-IcingaCheckSpoolerTutorial.ps1 + |_ Lib + | |_ Private + | |_ New-IcingaPlugin.ps1 + |_ Provider + | |_ Spooler + | |_ Private + | |_ Get-IcingaSpoolerQueue.ps1 + |_ Checks + |_ Public + |_ Invoke-IcingaCheckSpoolerTutorial.ps1 ``` > **Naming Rule:** Every check plugin function **must** begin with the prefix `Invoke-IcingaCheck`. `IcingaPlugin` inspects the call stack at construction time (`DetectCheckCommand()`) and uses the suffix after `Invoke-IcingaCheck` as the default `ifw_