Fixes various code stylings, whitespaces, line handling, and so on

This commit is contained in:
Christian Stein 2020-08-04 14:48:32 +02:00
parent 76f27caba4
commit ac02ec7e3e
69 changed files with 752 additions and 737 deletions

View file

@ -1,54 +1,54 @@
<# <#
.SYNOPSIS .SYNOPSIS
Will fetch the ticket for certificate signing by using the Icinga Director Will fetch the ticket for certificate signing by using the Icinga Director
Self-Service API Self-Service API
.DESCRIPTION .DESCRIPTION
Use the Self-Service API of the Icinga Director to connect to it and fetch the Use the Self-Service API of the Icinga Director to connect to it and fetch the
ticket to sign Icinga 2 certificate requests ticket to sign Icinga 2 certificate requests
.FUNCTIONALITY .FUNCTIONALITY
Fetches the ticket for certificate signing form the Icinga Director Self-Service API Fetches the ticket for certificate signing form the Icinga Director Self-Service API
.EXAMPLE .EXAMPLE
PS>Get-IcingaDirectorSelfServiceTicket -DirectorUrl 'https://example.com/icingaweb2/director -ApiKey 457g6b98054v76vb5490ß276bv0457v6054b76; PS>Get-IcingaDirectorSelfServiceTicket -DirectorUrl 'https://example.com/icingaweb2/director -ApiKey 457g6b98054v76vb5490ß276bv0457v6054b76;
.PARAMETER DirectorUrl .PARAMETER DirectorUrl
The URL pointing directly to the Icinga Web 2 Director module The URL pointing directly to the Icinga Web 2 Director module
.PARAMETER ApiKey .PARAMETER ApiKey
The host key to authenticate against the Self-Service API The host key to authenticate against the Self-Service API
.INPUTS .INPUTS
System.String System.String
.OUTPUTS .OUTPUTS
System.Object System.Object
.LINK .LINK
https://github.com/Icinga/icinga-powershell-framework https://github.com/Icinga/icinga-powershell-framework
#> #>
function Get-IcingaDirectorSelfServiceTicket() function Get-IcingaDirectorSelfServiceTicket()
{ {
param( param (
$DirectorUrl, $DirectorUrl,
$ApiKey = $null $ApiKey = $null
); );
if ([string]::IsNullOrEmpty($DirectorUrl)) { if ([string]::IsNullOrEmpty($DirectorUrl)) {
Write-IcingaConsoleError 'Unable to fetch host ticket. No Director url has been specified'; Write-IcingaConsoleError 'Unable to fetch host ticket. No Director url has been specified';
return; return;
} }
if ([string]::IsNullOrEmpty($ApiKey)) { if ([string]::IsNullOrEmpty($ApiKey)) {
Write-IcingaConsoleError 'Unable to fetch host ticket. No API key has been specified'; Write-IcingaConsoleError 'Unable to fetch host ticket. No API key has been specified';
return; return;
} }
Set-IcingaTLSVersion; Set-IcingaTLSVersion;
[string]$url = Join-WebPath -Path $DirectorUrl -ChildPath ([string]::Format('/self-service/ticket?key={0}', $ApiKey)); [string]$url = Join-WebPath -Path $DirectorUrl -ChildPath ([string]::Format('/self-service/ticket?key={0}', $ApiKey));
$response = Invoke-WebRequest -Uri $url -UseBasicParsing -Headers @{ 'accept' = 'application/json'; 'X-Director-Accept' = 'application/json' } -Method 'POST'; $response = Invoke-WebRequest -Uri $url -UseBasicParsing -Headers @{ 'accept' = 'application/json'; 'X-Director-Accept' = 'application/json' } -Method 'POST';
if ($response.StatusCode -ne 200) { if ($response.StatusCode -ne 200) {
throw $response.Content; throw $response.Content;
} }
$JsonContent = ConvertFrom-Json -InputObject $response.Content; $JsonContent = ConvertFrom-Json -InputObject $response.Content;
return $JsonContent; return $JsonContent;
} }

View file

@ -1,27 +1,27 @@
<# <#
.SYNOPSIS .SYNOPSIS
Reads data from a cache file of the Framework and returns its content Reads data from a cache file of the Framework and returns its content
.DESCRIPTION .DESCRIPTION
Allows a developer to read data from certain cache files to either speed up Allows a developer to read data from certain cache files to either speed up
loading procedures, to store content to not lose data on restarts of a daemon loading procedures, to store content to not lose data on restarts of a daemon
or to build data tables over time or to build data tables over time
.FUNCTIONALITY .FUNCTIONALITY
Returns cached data for specific content Returns cached data for specific content
.EXAMPLE .EXAMPLE
PS>Get-IcingaCacheData -Space 'sc_daemon' -CacheStore 'checkresult_store' -KeyName 'Invoke-IcingaCheckCPU'; PS>Get-IcingaCacheData -Space 'sc_daemon' -CacheStore 'checkresult_store' -KeyName 'Invoke-IcingaCheckCPU';
.PARAMETER Space .PARAMETER Space
The individual space to read from. This is targeted to a folder the cache data is written to under icinga-powershell-framework/cache/ The individual space to read from. This is targeted to a folder the cache data is written to under icinga-powershell-framework/cache/
.PARAMETER CacheStore .PARAMETER CacheStore
This is targeted to a sub-folder under icinga-powershell-framework/cache/<space>/ This is targeted to a sub-folder under icinga-powershell-framework/cache/<space>/
.PARAMETER KeyName .PARAMETER KeyName
This is the actual cache file located under icinga-powershell-framework/cache/<space>/<CacheStore>/<KeyName>.json This is the actual cache file located under icinga-powershell-framework/cache/<space>/<CacheStore>/<KeyName>.json
Please note to only provide the name without the '.json' apendix. This is done by the module itself Please note to only provide the name without the '.json' apendix. This is done by the module itself
.INPUTS .INPUTS
System.String System.String
.OUTPUTS .OUTPUTS
System.Object System.Object
.LINK .LINK
https://github.com/Icinga/icinga-powershell-framework https://github.com/Icinga/icinga-powershell-framework
.NOTES .NOTES
#> #>
function Get-IcingaCacheData() function Get-IcingaCacheData()

View file

@ -1,27 +1,27 @@
<# <#
.SYNOPSIS .SYNOPSIS
Writes data to a cache file for the Framework Writes data to a cache file for the Framework
.DESCRIPTION .DESCRIPTION
Allows a developer to write data to certain cache files to either speed up Allows a developer to write data to certain cache files to either speed up
loading procedures, to store content to not lose data on restarts of a daemon loading procedures, to store content to not lose data on restarts of a daemon
or to build data tables over time or to build data tables over time
.FUNCTIONALITY .FUNCTIONALITY
Writes data for specific value to a cache file Writes data for specific value to a cache file
.EXAMPLE .EXAMPLE
PS>Set-IcingaCacheData -Space 'sc_daemon' -CacheStore 'checkresult_store' -KeyName 'Invoke-IcingaCheckCPU' -Value @{ 'CachedData' = 'MyValue' }; PS>Set-IcingaCacheData -Space 'sc_daemon' -CacheStore 'checkresult_store' -KeyName 'Invoke-IcingaCheckCPU' -Value @{ 'CachedData' = 'MyValue' };
.PARAMETER Space .PARAMETER Space
The individual space to write to. This is targeted to a folder the cache data is written to under icinga-powershell-framework/cache/ The individual space to write to. This is targeted to a folder the cache data is written to under icinga-powershell-framework/cache/
.PARAMETER CacheStore .PARAMETER CacheStore
This is targeted to a sub-folder under icinga-powershell-framework/cache/<space>/ This is targeted to a sub-folder under icinga-powershell-framework/cache/<space>/
.PARAMETER KeyName .PARAMETER KeyName
This is the actual cache file located under icinga-powershell-framework/cache/<space>/<CacheStore>/<KeyName>.json This is the actual cache file located under icinga-powershell-framework/cache/<space>/<CacheStore>/<KeyName>.json
Please note to only provide the name without the '.json' apendix. This is done by the module itself Please note to only provide the name without the '.json' apendix. This is done by the module itself
.PARAMETER Value .PARAMETER Value
The actual value to store within the cache file. This can be any kind of value, as long as it is convertable to JSON The actual value to store within the cache file. This can be any kind of value, as long as it is convertable to JSON
.INPUTS .INPUTS
System.String System.String
.LINK .LINK
https://github.com/Icinga/icinga-powershell-framework https://github.com/Icinga/icinga-powershell-framework
.NOTES .NOTES
#> #>

View file

@ -18,7 +18,7 @@ function Get-IcingaWindowsInformation()
if ($ForceWMI -eq $FALSE -And (Get-Command 'Get-CimInstance' -ErrorAction SilentlyContinue)) { if ($ForceWMI -eq $FALSE -And (Get-Command 'Get-CimInstance' -ErrorAction SilentlyContinue)) {
try { try {
return (Get-CimInstance @Arguments -ErrorAction Stop) return (Get-CimInstance @Arguments -ErrorAction Stop);
} catch { } catch {
$ErrorName = $_.Exception.NativeErrorCode; $ErrorName = $_.Exception.NativeErrorCode;
$ErrorMessage = $_.Exception.Message; $ErrorMessage = $_.Exception.Message;
@ -43,7 +43,7 @@ function Get-IcingaWindowsInformation()
if ((Get-Command 'Get-WmiObject' -ErrorAction SilentlyContinue)) { if ((Get-Command 'Get-WmiObject' -ErrorAction SilentlyContinue)) {
try { try {
return (Get-WmiObject @Arguments -ErrorAction Stop) return (Get-WmiObject @Arguments -ErrorAction Stop);
} catch { } catch {
$ErrorName = $_.CategoryInfo.Category; $ErrorName = $_.CategoryInfo.Category;
$ErrorMessage = $_.Exception.Message; $ErrorMessage = $_.Exception.Message;

View file

@ -57,17 +57,17 @@ function Install-IcingaFrameworkComponent()
$ComponentName = $TextInfo.ToTitleCase($Name); $ComponentName = $TextInfo.ToTitleCase($Name);
$RepositoryName = [string]::Format('icinga-powershell-{0}', $Name); $RepositoryName = [string]::Format('icinga-powershell-{0}', $Name);
$Archive = Get-IcingaPowerShellModuleArchive ` $Archive = Get-IcingaPowerShellModuleArchive `
-DownloadUrl $Url ` -DownloadUrl $Url `
-GitHubUser $GitHubUser ` -GitHubUser $GitHubUser `
-ModuleName ( -ModuleName (
[string]::Format( [string]::Format(
'Icinga {0}', $ComponentName 'Icinga {0}', $ComponentName
) )
) ` ) `
-Repository $RepositoryName ` -Repository $RepositoryName `
-Release $Release ` -Release $Release `
-Snapshot $Snapshot ` -Snapshot $Snapshot `
-DryRun $DryRun; -DryRun $DryRun;
if ($Archive.Installed -eq $FALSE -Or $DryRun) { if ($Archive.Installed -eq $FALSE -Or $DryRun) {
return @{ return @{

View file

@ -31,9 +31,9 @@ function Install-IcingaFrameworkPlugins()
); );
[Hashtable]$Result = Install-IcingaFrameworkComponent ` [Hashtable]$Result = Install-IcingaFrameworkComponent `
-Name 'plugins' ` -Name 'plugins' `
-GitHubUser 'Icinga' ` -GitHubUser 'Icinga' `
-Url $PluginsUrl; -Url $PluginsUrl;
return @{ return @{
'PluginUrl' = $Result.RepoUrl; 'PluginUrl' = $Result.RepoUrl;

View file

@ -18,9 +18,10 @@ function Invoke-IcingaNamespaceCmdlets()
Import-Module $Cmdlet.Module.Path -WarningAction SilentlyContinue -ErrorAction Stop; Import-Module $Cmdlet.Module.Path -WarningAction SilentlyContinue -ErrorAction Stop;
$Content = (& $CmmandName); $Content = (& $CmmandName);
Add-IcingaHashtableItem -Hashtable $CommandConfig ` Add-IcingaHashtableItem `
-Key $Cmdlet.Name ` -Hashtable $CommandConfig `
-Value $Content | Out-Null; -Key $Cmdlet.Name `
-Value $Content | Out-Null;
} catch { } catch {
# TODO: Add event log logging on exceptions # TODO: Add event log logging on exceptions
} }

View file

@ -31,7 +31,6 @@ function Restart-IcingaService()
Restart-Service "$Service"; Restart-Service "$Service";
} -Args $Service; } -Args $Service;
} else { } else {
Write-IcingaConsoleWarning -Message 'The service "{0}" is not installed' -Objects $Service; Write-IcingaConsoleWarning -Message 'The service "{0}" is not installed' -Objects $Service;
} }

View file

@ -36,10 +36,12 @@ function Start-IcingaTimer()
$TimerObject = New-Object System.Diagnostics.Stopwatch; $TimerObject = New-Object System.Diagnostics.Stopwatch;
$TimerObject.Start(); $TimerObject.Start();
Add-IcingaHashtableItem -Key $Name -Value ([hashtable]::Synchronized( Add-IcingaHashtableItem -Key $Name -Value (
@{ [hashtable]::Synchronized(
'Active' = $TRUE; @{
'Timer' = $TimerObject; 'Active' = $TRUE;
} 'Timer' = $TimerObject;
)) -Hashtable $global:IcingaDaemonData.IcingaTimers -Override | Out-Null; }
)
) -Hashtable $global:IcingaDaemonData.IcingaTimers -Override | Out-Null;
} }

View file

@ -35,10 +35,12 @@ function Stop-IcingaTimer()
if ($TimerObject.IsRunning) { if ($TimerObject.IsRunning) {
$TimerObject.Stop(); $TimerObject.Stop();
} }
Add-IcingaHashtableItem -Key $Name -Value ([hashtable]::Synchronized( Add-IcingaHashtableItem -Key $Name -Value (
@{ [hashtable]::Synchronized(
'Active' = $FALSE; @{
'Timer' = $TimerObject; 'Active' = $FALSE;
} 'Timer' = $TimerObject;
)) -Hashtable $global:IcingaDaemonData.IcingaTimers -Override | Out-Null; }
)
) -Hashtable $global:IcingaDaemonData.IcingaTimers -Override | Out-Null;
} }

View file

@ -3,15 +3,19 @@ function Get-IcingaAgentFeatures()
$Binary = Get-IcingaAgentBinary; $Binary = Get-IcingaAgentBinary;
$ConfigResult = Start-IcingaProcess -Executable $Binary -Arguments 'feature list'; $ConfigResult = Start-IcingaProcess -Executable $Binary -Arguments 'feature list';
$DisabledFeatures = ($ConfigResult.Message.SubString( $DisabledFeatures = (
0, $ConfigResult.Message.SubString(
$ConfigResult.Message.IndexOf('Enabled features') 0,
)).Replace('Disabled features: ', '').Replace("`r`n", '').Replace("`r", '').Replace("`n", ''); $ConfigResult.Message.IndexOf('Enabled features')
)
).Replace('Disabled features: ', '').Replace("`r`n", '').Replace("`r", '').Replace("`n", '');
$EnabledFeatures = ($ConfigResult.Message.SubString( $EnabledFeatures = (
$ConfigResult.Message.IndexOf('Enabled features'), $ConfigResult.Message.SubString(
$ConfigResult.Message.Length - $ConfigResult.Message.IndexOf('Enabled features') $ConfigResult.Message.IndexOf('Enabled features'),
)).Replace('Enabled features: ', '').Replace("`r`n", '').Replace("`r", '').Replace("`n", ''); $ConfigResult.Message.Length - $ConfigResult.Message.IndexOf('Enabled features')
)
).Replace('Enabled features: ', '').Replace("`r`n", '').Replace("`r", '').Replace("`n", '');
return @{ return @{
'Enabled' = ($EnabledFeatures.Split(' ')); 'Enabled' = ($EnabledFeatures.Split(' '));

View file

@ -2,7 +2,7 @@ function Get-IcingaAgentInstallerAnswerInput()
{ {
param( param(
$Prompt, $Prompt,
[ValidateSet("y","n","v")] [ValidateSet("y", "n", "v")]
$Default, $Default,
$DefaultInput = '', $DefaultInput = '',
[switch]$Secure [switch]$Secure

View file

@ -29,11 +29,13 @@ function Install-IcingaAgent()
} }
$IcingaInstaller.Version = 'snapshot'; $IcingaInstaller.Version = 'snapshot';
} elseif ($IcingaInstaller.Version -eq $InstalledVersion.Full) { } elseif ($IcingaInstaller.Version -eq $InstalledVersion.Full) {
Write-IcingaConsoleNotice ([string]::Format( Write-IcingaConsoleNotice (
'No installation required. Your installed version [{0}] is matching the online version [{1}]', [string]::Format(
$InstalledVersion.Full, 'No installation required. Your installed version [{0}] is matching the online version [{1}]',
$IcingaInstaller.Version $InstalledVersion.Full,
)); $IcingaInstaller.Version
)
);
return $FALSE; return $FALSE;
} }

View file

@ -68,8 +68,8 @@ function Install-IcingaAgentCertificates()
if ((Start-IcingaAgentCertificateProcess -Arguments $arguments) -eq $FALSE) { if ((Start-IcingaAgentCertificateProcess -Arguments $arguments) -eq $FALSE) {
Write-IcingaConsoleError 'Unable to connect to your provided Icinga CA. Please verify the entered configuration is correct.' ` Write-IcingaConsoleError 'Unable to connect to your provided Icinga CA. Please verify the entered configuration is correct.' `
'If you are not able to connect to your Icinga CA from this machine, you will have to provide the path' ` 'If you are not able to connect to your Icinga CA from this machine, you will have to provide the path' `
'to your Icinga ca.crt and use the CA-Proxy certificate handling.'; 'to your Icinga ca.crt and use the CA-Proxy certificate handling.';
return $FALSE; return $FALSE;
} }
} }
@ -178,7 +178,7 @@ function Test-IcingaAgentCertificates()
} }
if ((-Not (Test-Path ((Join-Path -Path $CertDirectory -ChildPath $Hostname) + '.key'))) ` if ((-Not (Test-Path ((Join-Path -Path $CertDirectory -ChildPath $Hostname) + '.key'))) `
-Or -Not (Test-Path ((Join-Path -Path $CertDirectory -ChildPath $Hostname) + '.crt'))) { -Or -Not (Test-Path ((Join-Path -Path $CertDirectory -ChildPath $Hostname) + '.crt'))) {
return $FALSE; return $FALSE;
} }

View file

@ -19,7 +19,7 @@ function Start-IcingaAgentDirectorWizard()
if ($null -eq $OverrideDirectorVars -And $RunInstaller -eq $FALSE) { if ($null -eq $OverrideDirectorVars -And $RunInstaller -eq $FALSE) {
if ((Get-IcingaAgentInstallerAnswerInput -Prompt 'Do you want to manually override arguments provided by the Director API?' -Default 'n').result -eq 0) { if ((Get-IcingaAgentInstallerAnswerInput -Prompt 'Do you want to manually override arguments provided by the Director API?' -Default 'n').result -eq 0) {
$OverrideDirectorVars = $TRUE; $OverrideDirectorVars = $TRUE;
} else{ } else {
$OverrideDirectorVars = $FALSE; $OverrideDirectorVars = $FALSE;
} }
} }

View file

@ -563,11 +563,15 @@ function Start-IcingaAgentInstallWizard()
Write-IcingaAgentApiConfig -Port $CAPort; Write-IcingaAgentApiConfig -Port $CAPort;
if ($EmptyCA -eq $TRUE -Or $CertsInstalled -eq $FALSE) { if ($EmptyCA -eq $TRUE -Or $CertsInstalled -eq $FALSE) {
Disable-IcingaAgentFeature 'api'; Disable-IcingaAgentFeature 'api';
Write-IcingaConsoleWarning -Message '{0}{1}{2}{3}{4}' -Objects 'Your Icinga Agent API feature has been disabled. Please provide either your ca.crt ', Write-IcingaConsoleWarning `
'or connect to a parent node for certificate requests. You can run "Install-IcingaAgentCertificates" ', -Message '{0}{1}{2}{3}{4}' `
'with your configuration to properly create the host certificate and a valid certificate request. ', -Objects (
'After this you can enable the API feature by using "Enable-IcingaAgentFeature api" and restart the ', 'Your Icinga Agent API feature has been disabled. Please provide either your ca.crt ',
'Icinga Agent service "Restart-IcingaService icinga2"'; 'or connect to a parent node for certificate requests. You can run "Install-IcingaAgentCertificates" ',
'with your configuration to properly create the host certificate and a valid certificate request. ',
'After this you can enable the API feature by using "Enable-IcingaAgentFeature api" and restart the ',
'Icinga Agent service "Restart-IcingaService icinga2"'
);
} }
Write-IcingaAgentZonesConfig -Endpoints $Endpoints -EndpointConnections $EndpointConnections -ParentZone $ParentZone -GlobalZones $GlobalZoneConfig -Hostname $Hostname; Write-IcingaAgentZonesConfig -Endpoints $Endpoints -EndpointConnections $EndpointConnections -ParentZone $ParentZone -GlobalZones $GlobalZoneConfig -Hostname $Hostname;
if ($AddFirewallRule) { if ($AddFirewallRule) {
@ -733,9 +737,9 @@ function Set-IcingaWizardArgument()
if ([string]::IsNullOrEmpty($Value) -eq $FALSE) { if ([string]::IsNullOrEmpty($Value) -eq $FALSE) {
$InstallerArguments = Add-InstallerArgument ` $InstallerArguments = Add-InstallerArgument `
-InstallerArguments $InstallerArguments ` -InstallerArguments $InstallerArguments `
-Key $WizardArg ` -Key $WizardArg `
-Value $Value; -Value $Value;
return @{ return @{
'Value' = $Value; 'Value' = $Value;

View file

@ -17,7 +17,7 @@ function Set-IcingaAgentServiceUser()
} }
$ArgString = 'config {0} obj= "{1}" password= "{2}"'; $ArgString = 'config {0} obj= "{1}" password= "{2}"';
if($null -eq $Password) { if ($null -eq $Password) {
$ArgString = 'config {0} obj= "{1}"{2}'; $ArgString = 'config {0} obj= "{1}"{2}';
} }

View file

@ -5,7 +5,7 @@
# Example usage: # Example usage:
# $IcingaEventLogEnums[2000] # $IcingaEventLogEnums[2000]
#> #>
[hashtable]$IcingaEventLogEnums += @{ [hashtable]$IcingaEventLogEnums += @{
'Framework' = @{ 'Framework' = @{
1000 = @{ 1000 = @{
'EntryType' = 'Information'; 'EntryType' = 'Information';

View file

@ -1,38 +1,38 @@
<# <#
.SYNOPSIS .SYNOPSIS
Default Cmdlet for printing debug messages to console Default Cmdlet for printing debug messages to console
.DESCRIPTION .DESCRIPTION
Default Cmdlet for printing debug messages to console Default Cmdlet for printing debug messages to console
.FUNCTIONALITY .FUNCTIONALITY
Default Cmdlet for printing debug messages to console Default Cmdlet for printing debug messages to console
.EXAMPLE .EXAMPLE
PS>Write-IcingaConsoleDebug -Message 'Test message: {0}' -Objects 'Hello World'; PS>Write-IcingaConsoleDebug -Message 'Test message: {0}' -Objects 'Hello World';
.PARAMETER Message .PARAMETER Message
The message to print with {x} placeholdes replaced by content inside the Objects array. Replace x with the The message to print with {x} placeholdes replaced by content inside the Objects array. Replace x with the
number of the index from the objects array number of the index from the objects array
.PARAMETER Objects .PARAMETER Objects
An array of objects being added to a provided message. The index of the array position has to refer to the An array of objects being added to a provided message. The index of the array position has to refer to the
message locations. message locations.
.INPUTS .INPUTS
System.String System.String
.LINK .LINK
https://github.com/Icinga/icinga-powershell-framework https://github.com/Icinga/icinga-powershell-framework
#> #>
function Write-IcingaConsoleDebug() function Write-IcingaConsoleDebug()
{ {
param ( param (
[string]$Message, [string]$Message,
[array]$Objects [array]$Objects
); );
if ((Get-IcingaFrameworkDebugMode) -eq $FALSE) { if ((Get-IcingaFrameworkDebugMode) -eq $FALSE) {
return; return;
} }
Write-IcingaConsoleOutput ` Write-IcingaConsoleOutput `
-Message $Message ` -Message $Message `
-Objects $Objects ` -Objects $Objects `
-ForeColor 'Blue' ` -ForeColor 'Blue' `
-Severity 'Debug'; -Severity 'Debug';
} }

View file

@ -1,6 +1,6 @@
function Write-IcingaEventMessage() function Write-IcingaEventMessage()
{ {
param( param (
[int]$EventId = 0, [int]$EventId = 0,
[string]$Namespace = $null, [string]$Namespace = $null,
[array]$Objects = @() [array]$Objects = @()
@ -52,8 +52,8 @@ function Write-IcingaEventMessage()
} }
Write-EventLog -LogName Application ` Write-EventLog -LogName Application `
-Source 'Icinga for Windows' ` -Source 'Icinga for Windows' `
-EntryType $EntryType ` -EntryType $EntryType `
-EventId $EventId ` -EventId $EventId `
-Message $EventLogMessage; -Message $EventLogMessage;
} }

View file

@ -5,115 +5,115 @@
# which both contain the same members, allowing us to dynamicly use the objects # which both contain the same members, allowing us to dynamicly use the objects
# without having to worry about exception. # without having to worry about exception.
#> #>
function New-IcingaPerformanceCounter() function New-IcingaPerformanceCounter()
{ {
param( param(
[string]$Counter = '', [string]$Counter = '',
[boolean]$SkipWait = $FALSE [boolean]$SkipWait = $FALSE
); );
# Simply use the counter name, like # Simply use the counter name, like
# \Paging File(_total)\% Usage # \Paging File(_total)\% Usage
if ([string]::IsNullOrEmpty($Counter) -eq $TRUE) { if ([string]::IsNullOrEmpty($Counter) -eq $TRUE) {
return (New-IcingaPerformanceCounterNullObject -FullName $Counter -ErrorMessage 'Failed to initialise counter, as no counter was specified.'); return (New-IcingaPerformanceCounterNullObject -FullName $Counter -ErrorMessage 'Failed to initialise counter, as no counter was specified.');
} }
[array]$CounterArray = $Counter.Split('\'); [array]$CounterArray = $Counter.Split('\');
[string]$UseCounterCategory = ''; [string]$UseCounterCategory = '';
[string]$UseCounterName = ''; [string]$UseCounterName = '';
[string]$UseCounterInstance = ''; [string]$UseCounterInstance = '';
# If we add the counter as it should be # If we add the counter as it should be
# \Paging File(_total)\% Usage # \Paging File(_total)\% Usage
# the first array element will be an empty string we can skip # the first array element will be an empty string we can skip
# Otherwise the name was wrong and we should not continue # Otherwise the name was wrong and we should not continue
if (-Not [string]::IsNullOrEmpty($CounterArray[0])) { if (-Not [string]::IsNullOrEmpty($CounterArray[0])) {
return (New-IcingaPerformanceCounterNullObject -FullName $Counter -ErrorMessage ([string]::Format('Failed to deserialize counter "{0}". It seems the leading "\" is missing.', $Counter))); return (New-IcingaPerformanceCounterNullObject -FullName $Counter -ErrorMessage ([string]::Format('Failed to deserialize counter "{0}". It seems the leading "\" is missing.', $Counter)));
} }
# In case our Performance Counter is containing instances, we should split # In case our Performance Counter is containing instances, we should split
# The content and read the instance and counter category out # The content and read the instance and counter category out
if ($CounterArray[1].Contains('(')) { if ($CounterArray[1].Contains('(')) {
[array]$TmpCounter = $CounterArray[1].Split('('); [array]$TmpCounter = $CounterArray[1].Split('(');
$UseCounterCategory = $TmpCounter[0]; $UseCounterCategory = $TmpCounter[0];
$UseCounterInstance = $TmpCounter[1].Replace(')', ''); $UseCounterInstance = $TmpCounter[1].Replace(')', '');
} else { } else {
# Otherwise we only require the category # Otherwise we only require the category
$UseCounterCategory = $CounterArray[1]; $UseCounterCategory = $CounterArray[1];
} }
# At last get the actual counter containing our values # At last get the actual counter containing our values
$UseCounterName = $CounterArray[2]; $UseCounterName = $CounterArray[2];
# Now as we know how the counter path is constructed and has been splitted into # Now as we know how the counter path is constructed and has been splitted into
# the different values, we need to know how to handle the instances of the counter # the different values, we need to know how to handle the instances of the counter
# If we specify a instance with (*) we want the module to automaticly fetch all # If we specify a instance with (*) we want the module to automaticly fetch all
# instances for this counter. This will result in an New-IcingaPerformanceCounterResult # instances for this counter. This will result in an New-IcingaPerformanceCounterResult
# which contains the parent name including counters for all instances that # which contains the parent name including counters for all instances that
# have been found # have been found
if ($UseCounterInstance -eq '*') { if ($UseCounterInstance -eq '*') {
# In case we already loaded the counters once, return the finished array # In case we already loaded the counters once, return the finished array
# TODO: Re-Implement caching for counters # TODO: Re-Implement caching for counters
<#if ($Icinga2.Cache.PerformanceCounter.ContainsKey($Counter) -eq $TRUE) { <#if ($Icinga2.Cache.PerformanceCounter.ContainsKey($Counter) -eq $TRUE) {
return (New-IcingaPerformanceCounterResult -FullName $Counter -PerformanceCounters $Icinga2.Cache.PerformanceCounter[$Counter]); return (New-IcingaPerformanceCounterResult -FullName $Counter -PerformanceCounters $Icinga2.Cache.PerformanceCounter[$Counter]);
}#> }#>
# If we need to build the array, load all instances from the counters and # If we need to build the array, load all instances from the counters and
# create single performance counters and add them to a custom array and # create single performance counters and add them to a custom array and
# later to a custom object # later to a custom object
try { try {
[array]$AllCountersIntances = @(); [array]$AllCountersIntances = @();
$CounterInstances = New-Object System.Diagnostics.PerformanceCounterCategory($UseCounterCategory); $CounterInstances = New-Object System.Diagnostics.PerformanceCounterCategory($UseCounterCategory);
foreach ($instance in $CounterInstances.GetInstanceNames()) { foreach ($instance in $CounterInstances.GetInstanceNames()) {
[string]$NewCounterName = $Counter.Replace('*', $instance); [string]$NewCounterName = $Counter.Replace('*', $instance);
$NewCounter = New-IcingaPerformanceCounterObject -FullName $NewCounterName -Category $UseCounterCategory -Counter $UseCounterName -Instance $instance -SkipWait $TRUE; $NewCounter = New-IcingaPerformanceCounterObject -FullName $NewCounterName -Category $UseCounterCategory -Counter $UseCounterName -Instance $instance -SkipWait $TRUE;
$AllCountersIntances += $NewCounter; $AllCountersIntances += $NewCounter;
} }
} catch { } catch {
# Throw an exception in case our permissions are not enough to fetch performance counter # Throw an exception in case our permissions are not enough to fetch performance counter
Exit-IcingaThrowException -InputString $_.Exception -StringPattern 'System.UnauthorizedAccessException' -ExceptionType 'Permission' -ExceptionThrown $IcingaExceptions.Permission.PerformanceCounter; Exit-IcingaThrowException -InputString $_.Exception -StringPattern 'System.UnauthorizedAccessException' -ExceptionType 'Permission' -ExceptionThrown $IcingaExceptions.Permission.PerformanceCounter;
Exit-IcingaThrowException -InputString $_.Exception -StringPattern 'System.InvalidOperationException' -ExceptionType 'Input' -CustomMessage $Counter -ExceptionThrown $IcingaExceptions.Inputs.PerformanceCounter; Exit-IcingaThrowException -InputString $_.Exception -StringPattern 'System.InvalidOperationException' -ExceptionType 'Input' -CustomMessage $Counter -ExceptionThrown $IcingaExceptions.Inputs.PerformanceCounter;
Exit-IcingaThrowException -InputString $_.Exception -StringPattern '' -ExceptionType 'Unhandled'; Exit-IcingaThrowException -InputString $_.Exception -StringPattern '' -ExceptionType 'Unhandled';
# Shouldn't actually get down here anyways # Shouldn't actually get down here anyways
return (New-IcingaPerformanceCounterNullObject -FullName $Counter -ErrorMessage ([string]::Format('Failed to deserialize instances for counter "{0}". Exception: "{1}".', $Counter, $_.Exception.Message))); return (New-IcingaPerformanceCounterNullObject -FullName $Counter -ErrorMessage ([string]::Format('Failed to deserialize instances for counter "{0}". Exception: "{1}".', $Counter, $_.Exception.Message)));
} }
# If we load multiple instances, we should add a global wait here instead of a wait for each single instance # If we load multiple instances, we should add a global wait here instead of a wait for each single instance
# This will speed up CPU loading for example with plenty of cores avaiable # This will speed up CPU loading for example with plenty of cores avaiable
if ($SkipWait -eq $FALSE) { if ($SkipWait -eq $FALSE) {
Start-Sleep -Milliseconds 500; Start-Sleep -Milliseconds 500;
} }
# Add the parent counter including the array of Performance Counters to our # Add the parent counter including the array of Performance Counters to our
# caching mechanism and return the New-IcingaPerformanceCounterResult object for usage # caching mechanism and return the New-IcingaPerformanceCounterResult object for usage
# within the monitoring modules # within the monitoring modules
# TODO: Re-Implement caching for counters # TODO: Re-Implement caching for counters
# $Icinga2.Cache.PerformanceCounter.Add($Counter, $AllCountersIntances); # $Icinga2.Cache.PerformanceCounter.Add($Counter, $AllCountersIntances);
return (New-IcingaPerformanceCounterResult -FullName $Counter -PerformanceCounters $AllCountersIntances); return (New-IcingaPerformanceCounterResult -FullName $Counter -PerformanceCounters $AllCountersIntances);
} else { } else {
# This part will handle the counters without any instances as well as # This part will handle the counters without any instances as well as
# specificly assigned instances, like (_Total) CPU usage. # specificly assigned instances, like (_Total) CPU usage.
# In case we already have the counter within our cache, return the # In case we already have the counter within our cache, return the
# cached informations # cached informations
# TODO: Re-Implement caching for counters # TODO: Re-Implement caching for counters
<#if ($Icinga2.Cache.PerformanceCounter.ContainsKey($Counter) -eq $TRUE) { <#if ($Icinga2.Cache.PerformanceCounter.ContainsKey($Counter) -eq $TRUE) {
return $Icinga2.Cache.PerformanceCounter[$Counter]; return $Icinga2.Cache.PerformanceCounter[$Counter];
}#> }#>
# If the cache is not present yet, create the Performance Counter object, # If the cache is not present yet, create the Performance Counter object,
# and add it to our cache # and add it to our cache
$NewCounter = New-IcingaPerformanceCounterObject -FullName $Counter -Category $UseCounterCategory -Counter $UseCounterName -Instance $UseCounterInstance -SkipWait $SkipWait; $NewCounter = New-IcingaPerformanceCounterObject -FullName $Counter -Category $UseCounterCategory -Counter $UseCounterName -Instance $UseCounterInstance -SkipWait $SkipWait;
# TODO: Re-Implement caching for counters # TODO: Re-Implement caching for counters
#$Icinga2.Cache.PerformanceCounter.Add($Counter, $NewCounter); #$Icinga2.Cache.PerformanceCounter.Add($Counter, $NewCounter);
return $NewCounter; #TODO: Remove once caching is implemented return $NewCounter; #TODO: Remove once caching is implemented
} }
# This function will always return non-instance counters or # This function will always return non-instance counters or
# specificly defined instance counters. Performance Counter Arrays # specificly defined instance counters. Performance Counter Arrays
# are returned within their function. This is just to ensure that the # are returned within their function. This is just to ensure that the
# function looks finished from developer point of view # function looks finished from developer point of view
# TODO: Re-Implement caching for counters, right now we return $NewCounter by default # TODO: Re-Implement caching for counters, right now we return $NewCounter by default
#return $Icinga2.Cache.PerformanceCounter[$Counter]; #return $Icinga2.Cache.PerformanceCounter[$Counter];
} }

View file

@ -5,33 +5,32 @@
# the same member functions but allowing us to maintain # the same member functions but allowing us to maintain
# stability without unwanted exceptions # stability without unwanted exceptions
#> #>
function New-IcingaPerformanceCounterNullObject() function New-IcingaPerformanceCounterNullObject()
{ {
param( param(
[string]$FullName = '', [string]$FullName = '',
[string]$ErrorMessage = '' [string]$ErrorMessage = ''
); );
$pc_instance = New-Object -TypeName PSObject; $pc_instance = New-Object -TypeName PSObject;
$pc_instance | Add-Member -membertype NoteProperty -name 'FullName' -value $FullName; $pc_instance | Add-Member -MemberType NoteProperty -Name 'FullName' -Value $FullName;
$pc_instance | Add-Member -membertype NoteProperty -name 'ErrorMessage' -value $ErrorMessage; $pc_instance | Add-Member -MemberType NoteProperty -Name 'ErrorMessage' -Value $ErrorMessage;
$pc_instance | Add-Member -membertype ScriptMethod -name 'Name' -value { $pc_instance | Add-Member -MemberType ScriptMethod -Name 'Name' -Value {
return $this.FullName; return $this.FullName;
} }
$pc_instance | Add-Member -membertype ScriptMethod -name 'Value' -value { $pc_instance | Add-Member -MemberType ScriptMethod -Name 'Value' -Value {
[hashtable]$ErrorMessage = @{}; [hashtable]$ErrorMessage = @{};
$ErrorMessage.Add('value', $null); $ErrorMessage.Add('value', $null);
$ErrorMessage.Add('sample', $null); $ErrorMessage.Add('sample', $null);
$ErrorMessage.Add('help', $null); $ErrorMessage.Add('help', $null);
$ErrorMessage.Add('type', $null); $ErrorMessage.Add('type', $null);
$ErrorMessage.Add('error', $this.ErrorMessage); $ErrorMessage.Add('error', $this.ErrorMessage);
return $ErrorMessage; return $ErrorMessage;
} }
return $pc_instance;
}
return $pc_instance;
}

View file

@ -9,93 +9,93 @@
# of the counter. Within the New-IcingaPerformanceCounterResult function, # of the counter. Within the New-IcingaPerformanceCounterResult function,
# objects created by this function are used. # objects created by this function are used.
#> #>
function New-IcingaPerformanceCounterObject() function New-IcingaPerformanceCounterObject()
{ {
param( param(
[string]$FullName = '', [string]$FullName = '',
[string]$Category = '', [string]$Category = '',
[string]$Instance = '', [string]$Instance = '',
[string]$Counter = '', [string]$Counter = '',
[boolean]$SkipWait = $FALSE [boolean]$SkipWait = $FALSE
); );
$pc_instance = New-Object -TypeName PSObject; $pc_instance = New-Object -TypeName PSObject;
$pc_instance | Add-Member -membertype NoteProperty -name 'FullName' -value $FullName; $pc_instance | Add-Member -MemberType NoteProperty -Name 'FullName' -Value $FullName;
$pc_instance | Add-Member -membertype NoteProperty -name 'Category' -value $Category; $pc_instance | Add-Member -MemberType NoteProperty -Name 'Category' -Value $Category;
$pc_instance | Add-Member -membertype NoteProperty -name 'Instance' -value $Instance; $pc_instance | Add-Member -MemberType NoteProperty -Name 'Instance' -Value $Instance;
$pc_instance | Add-Member -membertype NoteProperty -name 'Counter' -value $Counter; $pc_instance | Add-Member -MemberType NoteProperty -Name 'Counter' -Value $Counter;
$pc_instance | Add-Member -membertype NoteProperty -name 'PerfCounter' -value $Counter; $pc_instance | Add-Member -MemberType NoteProperty -Name 'PerfCounter' -Value $Counter;
$pc_instance | Add-Member -membertype NoteProperty -name 'SkipWait' -value $SkipWait; $pc_instance | Add-Member -MemberType NoteProperty -Name 'SkipWait' -Value $SkipWait;
$pc_instance | Add-Member -membertype ScriptMethod -name 'Init' -value { $pc_instance | Add-Member -MemberType ScriptMethod -Name 'Init' -Value {
Write-IcingaConsoleDebug ` Write-IcingaConsoleDebug `
-Message 'Creating new Counter for Category "{0}" with Instance "{1}" and Counter "{2}". Full Name "{3}"' ` -Message 'Creating new Counter for Category "{0}" with Instance "{1}" and Counter "{2}". Full Name "{3}"' `
-Objects $this.Category, $this.Instance, $this.Counter, $this.FullName; -Objects $this.Category, $this.Instance, $this.Counter, $this.FullName;
# Create the Performance Counter object we want to access # Create the Performance Counter object we want to access
$this.PerfCounter = New-Object System.Diagnostics.PerformanceCounter; $this.PerfCounter = New-Object System.Diagnostics.PerformanceCounter;
$this.PerfCounter.CategoryName = $this.Category; $this.PerfCounter.CategoryName = $this.Category;
$this.PerfCounter.CounterName = $this.Counter; $this.PerfCounter.CounterName = $this.Counter;
# Only add an instance in case it is defined # Only add an instance in case it is defined
if ([string]::IsNullOrEmpty($this.Instance) -eq $FALSE) { if ([string]::IsNullOrEmpty($this.Instance) -eq $FALSE) {
$this.PerfCounter.InstanceName = $this.Instance $this.PerfCounter.InstanceName = $this.Instance
} }
# Initialise the counter # Initialise the counter
try { try {
$this.PerfCounter.NextValue() | Out-Null; $this.PerfCounter.NextValue() | Out-Null;
} catch { } catch {
# Nothing to do here, will be handled later # Nothing to do here, will be handled later
} }
<# <#
# For some counters we require to wait a small amount of time to receive proper data # For some counters we require to wait a small amount of time to receive proper data
# Other counters do not need these informations and we do also not require to wait # Other counters do not need these informations and we do also not require to wait
# for every counter we use, once the counter is initialised within our environment. # for every counter we use, once the counter is initialised within our environment.
# This will allow us to skip the sleep to speed up loading counters # This will allow us to skip the sleep to speed up loading counters
#> #>
if ($this.SkipWait -eq $FALSE) { if ($this.SkipWait -eq $FALSE) {
Start-Sleep -Milliseconds 500; Start-Sleep -Milliseconds 500;
} }
} }
# Return the name of the counter as string # Return the name of the counter as string
$pc_instance | Add-Member -membertype ScriptMethod -name 'Name' -value { $pc_instance | Add-Member -MemberType ScriptMethod -Name 'Name' -Value {
return $this.FullName; return $this.FullName;
} }
<# <#
# Return a hashtable containting the counter value including the # Return a hashtable containting the counter value including the
# Sample values for the counter itself. In case we run into an error, # Sample values for the counter itself. In case we run into an error,
# keep the counter construct but add an error message in addition. # keep the counter construct but add an error message in addition.
#> #>
$pc_instance | Add-Member -membertype ScriptMethod -name 'Value' -value { $pc_instance | Add-Member -MemberType ScriptMethod -Name 'Value' -Value {
[hashtable]$CounterData = @{}; [hashtable]$CounterData = @{};
try { try {
[string]$CounterType = $this.PerfCounter.CounterType; [string]$CounterType = $this.PerfCounter.CounterType;
$CounterData.Add('value', $this.PerfCounter.NextValue()); $CounterData.Add('value', $this.PerfCounter.NextValue());
$CounterData.Add('sample', $this.PerfCounter.NextSample()); $CounterData.Add('sample', $this.PerfCounter.NextSample());
$CounterData.Add('help', $this.PerfCounter.CounterHelp); $CounterData.Add('help', $this.PerfCounter.CounterHelp);
$CounterData.Add('type', $CounterType); $CounterData.Add('type', $CounterType);
$CounterData.Add('error', $null); $CounterData.Add('error', $null);
} catch { } catch {
$CounterData = @{}; $CounterData = @{};
$CounterData.Add('value', $null); $CounterData.Add('value', $null);
$CounterData.Add('sample', $null); $CounterData.Add('sample', $null);
$CounterData.Add('help', $null); $CounterData.Add('help', $null);
$CounterData.Add('type', $null); $CounterData.Add('type', $null);
$CounterData.Add('error', $_.Exception.Message); $CounterData.Add('error', $_.Exception.Message);
} }
return $CounterData; return $CounterData;
} }
# Initialiste the entire counter and internal handlers # Initialiste the entire counter and internal handlers
$pc_instance.Init(); $pc_instance.Init();
# Return this custom object # Return this custom object
return $pc_instance; return $pc_instance;
} }

View file

@ -9,30 +9,30 @@
# containing the parent counter name including the values and # containing the parent counter name including the values and
# samples for every single instance # samples for every single instance
#> #>
function New-IcingaPerformanceCounterResult() function New-IcingaPerformanceCounterResult()
{ {
param( param(
[string]$FullName = '', [string]$FullName = '',
[array]$PerformanceCounters = @() [array]$PerformanceCounters = @()
); );
$pc_instance = New-Object -TypeName PSObject; $pc_instance = New-Object -TypeName PSObject;
$pc_instance | Add-Member -membertype NoteProperty -name 'FullName' -value $FullName; $pc_instance | Add-Member -MemberType NoteProperty -Name 'FullName' -Value $FullName;
$pc_instance | Add-Member -membertype NoteProperty -name 'Counters' -value $PerformanceCounters; $pc_instance | Add-Member -MemberType NoteProperty -Name 'Counters' -Value $PerformanceCounters;
$pc_instance | Add-Member -membertype ScriptMethod -name 'Name' -value { $pc_instance | Add-Member -MemberType ScriptMethod -Name 'Name' -Value {
return $this.FullName; return $this.FullName;
} }
$pc_instance | Add-Member -membertype ScriptMethod -name 'Value' -value { $pc_instance | Add-Member -MemberType ScriptMethod -Name 'Value' -Value {
[hashtable]$CounterResults = @{}; [hashtable]$CounterResults = @{};
foreach ($counter in $this.Counters) { foreach ($counter in $this.Counters) {
$CounterResults.Add($counter.Name(), $counter.Value()); $CounterResults.Add($counter.Name(), $counter.Value());
} }
return $CounterResults; return $CounterResults;
} }
return $pc_instance; return $pc_instance;
} }

View file

@ -5,8 +5,9 @@
# #
function Show-IcingaPerformanceCounterCategories() function Show-IcingaPerformanceCounterCategories()
{ {
$RegistryData = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009' ` $RegistryData = Get-ItemProperty `
-Name 'counter' | Select-Object -ExpandProperty Counter; -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009' `
-Name 'counter' | Select-Object -ExpandProperty Counter;
[array]$Counters = @(); [array]$Counters = @();
# Now lets loop our registry data and fetch only for counter categories # Now lets loop our registry data and fetch only for counter categories

View file

@ -1,8 +1,8 @@
function Convert-Bytes() function Convert-Bytes()
{ {
param( param(
[string]$Value, [string]$Value,
[string]$Unit [string]$Unit
); );
If (($Value -Match "(^[\d\.]*) ?(B|KB|MB|GB|TB|PT|KiB|MiB|GiB|TiB|PiB)")) { If (($Value -Match "(^[\d\.]*) ?(B|KB|MB|GB|TB|PT|KiB|MiB|GiB|TiB|PiB)")) {
@ -10,23 +10,22 @@ function Convert-Bytes()
[string]$CurrentUnit = $Matches[2]; [string]$CurrentUnit = $Matches[2];
switch ($CurrentUnit) { switch ($CurrentUnit) {
{ 'KiB', 'MiB', 'GiB', 'TiB', 'PiB' -contains $_} { $CurrentValue = ConvertTo-ByteIEC $CurrentValue $CurrentUnit; $boolOption = $true;} { 'KiB', 'MiB', 'GiB', 'TiB', 'PiB' -contains $_ } { $CurrentValue = ConvertTo-ByteIEC $CurrentValue $CurrentUnit; $boolOption = $true; }
{ 'KB', 'MB', 'GB', 'TB', 'PB' -contains $_} { $CurrentValue = ConvertTo-ByteSI $CurrentValue $CurrentUnit; $boolOption = $true;} { 'KB', 'MB', 'GB', 'TB', 'PB' -contains $_ } { $CurrentValue = ConvertTo-ByteSI $CurrentValue $CurrentUnit; $boolOption = $true; }
} }
switch ($Unit) { switch ($Unit) {
{ 'B' -contains $_} { $FinalValue = $CurrentValue; $boolOption = $true;} { 'B' -contains $_ } { $FinalValue = $CurrentValue; $boolOption = $true; }
{ 'KB' -contains $_} { $FinalValue = ConvertTo-Kilobyte $CurrentValue -Unit B; $boolOption = $true;} { 'KB' -contains $_ } { $FinalValue = ConvertTo-Kilobyte $CurrentValue -Unit B; $boolOption = $true; }
{ 'MB' -contains $_} { $FinalValue = ConvertTo-Megabyte $CurrentValue -Unit B; $boolOption = $true;} { 'MB' -contains $_ } { $FinalValue = ConvertTo-Megabyte $CurrentValue -Unit B; $boolOption = $true; }
{ 'GB' -contains $_} { $FinalValue = ConvertTo-Gigabyte $CurrentValue -Unit B; $boolOption = $true;} { 'GB' -contains $_ } { $FinalValue = ConvertTo-Gigabyte $CurrentValue -Unit B; $boolOption = $true; }
{ 'TB' -contains $_} { $FinalValue = ConvertTo-Terabyte $CurrentValue -Unit B; $boolOption = $true;} { 'TB' -contains $_ } { $FinalValue = ConvertTo-Terabyte $CurrentValue -Unit B; $boolOption = $true; }
{ 'PB' -contains $_} { $FinalValue = ConvertTo-Petabyte $CurrentValue -Unit B; $boolOption = $true;} { 'PB' -contains $_ } { $FinalValue = ConvertTo-Petabyte $CurrentValue -Unit B; $boolOption = $true; }
{ 'KiB' -contains $_} { $FinalValue = ConvertTo-Kibibyte $CurrentValue -Unit B; $boolOption = $true;} { 'KiB' -contains $_ } { $FinalValue = ConvertTo-Kibibyte $CurrentValue -Unit B; $boolOption = $true; }
{ 'MiB' -contains $_} { $FinalValue = ConvertTo-Mebibyte $CurrentValue -Unit B; $boolOption = $true;} { 'MiB' -contains $_ } { $FinalValue = ConvertTo-Mebibyte $CurrentValue -Unit B; $boolOption = $true; }
{ 'GiB' -contains $_} { $FinalValue = ConvertTo-Gibibyte $CurrentValue -Unit B; $boolOption = $true;} { 'GiB' -contains $_ } { $FinalValue = ConvertTo-Gibibyte $CurrentValue -Unit B; $boolOption = $true; }
{ 'TiB' -contains $_} { $FinalValue = ConvertTo-Tebibyte $CurrentValue -Unit B; $boolOption = $true;} { 'TiB' -contains $_ } { $FinalValue = ConvertTo-Tebibyte $CurrentValue -Unit B; $boolOption = $true; }
{ 'PiB' -contains $_} { $FinalValue = ConvertTo-Petabyte $CurrentValue -Unit B; $boolOption = $true;} { 'PiB' -contains $_ } { $FinalValue = ConvertTo-Petabyte $CurrentValue -Unit B; $boolOption = $true; }
default { default {
if (-Not $boolOption) { if (-Not $boolOption) {
@ -34,7 +33,7 @@ function Convert-Bytes()
} }
} }
} }
return @{'value' = $FinalValue; 'pastunit' = $CurrentUnit; 'endunit' = $Unit}; return @{'value' = $FinalValue; 'pastunit' = $CurrentUnit; 'endunit' = $Unit };
} }
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force; Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;

View file

@ -1,8 +1,8 @@
function ConvertTo-ByteIEC() function ConvertTo-ByteIEC()
{ {
param( param(
[single]$Value, [single]$Value,
[string]$Unit [string]$Unit
); );
switch ($Unit) { switch ($Unit) {

View file

@ -17,8 +17,8 @@
function ConvertTo-ByteSI() function ConvertTo-ByteSI()
{ {
param( param(
[single]$Value, [single]$Value,
[string]$Unit [string]$Unit
); );
switch ($Unit) { switch ($Unit) {

View file

@ -1,37 +1,37 @@
<# <#
.SYNOPSIS .SYNOPSIS
Used to convert both IPv4 addresses and IPv6 addresses to binary. Used to convert both IPv4 addresses and IPv6 addresses to binary.
.DESCRIPTION .DESCRIPTION
ConvertTo-IcingaIPBinaryString returns a binary string based on the given IPv4 address or IPv6 address. ConvertTo-IcingaIPBinaryString returns a binary string based on the given IPv4 address or IPv6 address.
More Information on https://github.com/Icinga/icinga-powershell-framework More Information on https://github.com/Icinga/icinga-powershell-framework
.FUNCTIONALITY .FUNCTIONALITY
This module is intended to be used to convert an IPv4 address or IPv6 address to binary string. This module is intended to be used to convert an IPv4 address or IPv6 address to binary string.
.PARAMETER IP .PARAMETER IP
Used to specify an IPv4 address or IPv6 address. Used to specify an IPv4 address or IPv6 address.
.INPUTS .INPUTS
System.String System.String
.OUTPUTS .OUTPUTS
System.String System.String
.LINK .LINK
https://github.com/Icinga/icinga-powershell-framework https://github.com/Icinga/icinga-powershell-framework
.NOTES .NOTES
#> #>
function ConvertTo-IcingaIPBinaryString() function ConvertTo-IcingaIPBinaryString()
{ {
param( param (
$IP $IP
); );
if ($IP -like '*.*') { if ($IP -like '*.*') {
$IP = ConvertTo-IcingaIPv4BinaryString -IP $IP; $IP = ConvertTo-IcingaIPv4BinaryString -IP $IP;
} elseif ($IP -like '*:*') { } elseif ($IP -like '*:*') {
$IP = ConvertTo-IcingaIPv6BinaryString -IP $IP; $IP = ConvertTo-IcingaIPv6BinaryString -IP $IP;
} else { } else {
return 'Invalid IP was provided!'; return 'Invalid IP was provided!';
} }
return $IP; return $IP;
} }

View file

@ -21,24 +21,24 @@
function ConvertTo-IcingaIPv4BinaryString() function ConvertTo-IcingaIPv4BinaryString()
{ {
param( param(
[string]$IP [string]$IP
); );
try { try {
$IP = $IP -split '\.' | ForEach-Object { $IP = $IP -split '\.' | ForEach-Object {
[System.Convert]::ToString($_, 2).PadLeft(8, '0'); [System.Convert]::ToString($_, 2).PadLeft(8, '0');
} }
$IP = $IP -join ''; $IP = $IP -join '';
$IP = $IP -replace '\s',''; $IP = $IP -replace '\s', '';
} catch { } catch {
# Todo: Should we handle errors? It might happen due to faulty routes or unhandled route config # Todo: Should we handle errors? It might happen due to faulty routes or unhandled route config
# we throw errors which should have no effect at all # we throw errors which should have no effect at all
return $null; return $null;
} }
return @{ return @{
'value' = $IP; 'value' = $IP;
'name' = 'IPv4' 'name' = 'IPv4'
} }
} }

View file

@ -29,13 +29,13 @@ function ConvertTo-IcingaIPv6BinaryString()
$IPArr = $IPArr.ToCharArray(); $IPArr = $IPArr.ToCharArray();
$IP = $IPArr | ForEach-Object { $IP = $IPArr | ForEach-Object {
[System.Convert]::ToString("0x$_",2).PadLeft(4, '0'); [System.Convert]::ToString("0x$_", 2).PadLeft(4, '0');
} }
$IP = $IP -join ''; $IP = $IP -join '';
$IP = $IP -replace '\s',''; $IP = $IP -replace '\s', '';
return @{ return @{
'value' = $IP; 'value' = $IP;
'name' = 'IPv6' 'name' = 'IPv6'
} }
} }

View file

@ -37,7 +37,7 @@ function ConvertTo-Seconds()
[bool]$Negate = $FALSE; [bool]$Negate = $FALSE;
[bool]$hasUnit = $FALSE; [bool]$hasUnit = $FALSE;
foreach($char in $Value.ToCharArray()) { foreach ($char in $Value.ToCharArray()) {
if ((Test-Numeric $char)) { if ((Test-Numeric $char)) {
$NumberPart += $char; $NumberPart += $char;
} else { } else {

View file

@ -34,7 +34,7 @@ function Expand-IcingaIPv6String()
for ($Index = 0; $Index -lt $IP.Length; $Index++) { for ($Index = 0; $Index -lt $IP.Length; $Index++) {
if ($IP[$Index] -eq ':') { if ($IP[$Index] -eq ':') {
$Counter++; $Counter++;
if (($Index - 1) -ge 0 -and $IP[$Index - 1] -eq ':'){ if (($Index - 1) -ge 0 -and $IP[$Index - 1] -eq ':') {
$RelV = $Index; $RelV = $Index;
} }
} }

View file

@ -64,7 +64,6 @@
function Get-IcingaCheckCommandConfig() function Get-IcingaCheckCommandConfig()
{ {
param( param(
[Parameter(ValueFromPipeline)]
[array]$CheckName, [array]$CheckName,
[string]$OutDirectory [string]$OutDirectory
); );
@ -74,7 +73,7 @@ function Get-IcingaCheckCommandConfig()
$CheckName = (Get-Command Invoke-IcingaCheck*).Name $CheckName = (Get-Command Invoke-IcingaCheck*).Name
} }
[int]$FieldID = 2; # Starts at '2', because '0' and '1' are reserved for 'Verbose' and 'NoPerfData' [int]$FieldID = 2; # Starts at '2', because '0' and '1' are reserved for 'Verbose' and 'NoPerfData'
[hashtable]$Basket = @{}; [hashtable]$Basket = @{};
# Define basic hashtable structure by adding fields: "Datafield", "DataList", "Command" # Define basic hashtable structure by adding fields: "Datafield", "DataList", "Command"
@ -159,8 +158,8 @@ function Get-IcingaCheckCommandConfig()
$Basket.Command[$Data.Name].vars.Add($parameter.Name, $FALSE); $Basket.Command[$Data.Name].vars.Add($parameter.Name, $FALSE);
# Conditional whether type of parameter is array
} elseif ($parameter.type.name -eq 'Array') { } elseif ($parameter.type.name -eq 'Array') {
# Conditional whether type of parameter is array
$Basket.Command[$Data.Name].arguments.Add( $Basket.Command[$Data.Name].arguments.Add(
[string]::Format('-{0}', $parameter.Name), @{ [string]::Format('-{0}', $parameter.Name), @{
'value' = @{ 'value' = @{

View file

@ -59,26 +59,19 @@ function Get-IcingaNetworkInterface()
foreach ($destinationIP in $IPBinStringMaster) { foreach ($destinationIP in $IPBinStringMaster) {
[string]$Key = ''; [string]$Key = '';
[string]$MaskKey = ''; [string]$MaskKey = '';
############################################################################ <# IPv4 #>
################################ IPv4 ####################################
############################################################################
if ($destinationIP.name -eq 'IPv4') { if ($destinationIP.name -eq 'IPv4') {
if ($IP -like '*.*') { if ($IP -like '*.*') {
############################################################################
if ([int]$Mask -lt 10) { if ([int]$Mask -lt 10) {
$MaskKey = [string]::Format('00{0}', $Mask); $MaskKey = [string]::Format('00{0}', $Mask);
} else { } else {
$MaskKey = [string]::Format('0{0}', $Mask); $MaskKey = [string]::Format('0{0}', $Mask);
} }
############################################################################
} }
} }
############################################################################ <# IPv6 #>
################################ IPv6 ####################################
############################################################################
if ($destinationIP.name -eq 'IPv6') { if ($destinationIP.name -eq 'IPv6') {
if ($IP -like '*:*') { if ($IP -like '*:*') {
############################################################################
if ([int]$Mask -lt 10) { if ([int]$Mask -lt 10) {
$MaskKey = [string]::Format('00{0}', $Mask); $MaskKey = [string]::Format('00{0}', $Mask);
} elseif ([int]$Mask -lt 100) { } elseif ([int]$Mask -lt 100) {
@ -86,7 +79,6 @@ function Get-IcingaNetworkInterface()
} else { } else {
$MaskKey = $Mask; $MaskKey = $Mask;
} }
############################################################################
} }
} }
@ -144,7 +136,7 @@ function Get-IcingaNetworkInterface()
if ($ExternalInterfaces.Count -eq 0) { if ($ExternalInterfaces.Count -eq 0) {
foreach ($destinationIP in $IPBinStringMaster) { foreach ($destinationIP in $IPBinStringMaster) {
$ExternalInterface = ((Get-NetIPAddress -InterfaceIndex (Get-NetRoute | Where-Object -Property DestinationPrefix -like '0.0.0.0/0')[0].IfIndex -AddressFamily $destinationIP.name).IPAddress).split('%')[0]; $ExternalInterface = ((Get-NetIPAddress -InterfaceIndex (Get-NetRoute | Where-Object -Property DestinationPrefix -Like '0.0.0.0/0')[0].IfIndex -AddressFamily $destinationIP.name).IPAddress).split('%')[0];
if ($ExternalInterfaces.ContainsKey($ExternalInterface)) { if ($ExternalInterfaces.ContainsKey($ExternalInterface)) {
$ExternalInterfaces[$ExternalInterface].count += 1; $ExternalInterfaces[$ExternalInterface].count += 1;
} else { } else {

View file

@ -1,6 +1,6 @@
function Get-StringSha1() function Get-StringSha1()
{ {
param( param (
[string]$Content [string]$Content
); );
@ -9,8 +9,8 @@ function Get-StringSha1()
$ContentBytes = $CryptoAlgorithm.ComputeHash($ContentHash); $ContentBytes = $CryptoAlgorithm.ComputeHash($ContentHash);
$OutputHash = ''; $OutputHash = '';
foreach($byte in $ContentBytes) { foreach ($byte in $ContentBytes) {
$OutputHash += $byte.ToString() $OutputHash += $byte.ToString()
} }
return $OutputHash; return $OutputHash;

View file

@ -1,7 +1,7 @@
function Get-UnitPrefixIEC() function Get-UnitPrefixIEC()
{ {
param( param(
[single]$Value [single]$Value
); );
If ( $Value / [math]::Pow(2, 50) -ge 1 ) { If ( $Value / [math]::Pow(2, 50) -ge 1 ) {

View file

@ -1,7 +1,7 @@
function Get-UnitPrefixSI() function Get-UnitPrefixSI()
{ {
param( param(
[single]$Value [single]$Value
); );
If ( $Value / [math]::Pow(10, 15) -ge 1 ) { If ( $Value / [math]::Pow(10, 15) -ge 1 ) {

View file

@ -2,7 +2,7 @@ Import-IcingaLib icinga\plugin;
function Get-IcingaHelpThresholds() function Get-IcingaHelpThresholds()
{ {
param( param (
$Value, $Value,
$Warning, $Warning,
$Critical $Critical

View file

@ -5,7 +5,7 @@ function Exit-IcingaThrowException()
[string]$StringPattern, [string]$StringPattern,
[string]$CustomMessage, [string]$CustomMessage,
[string]$ExceptionThrown, [string]$ExceptionThrown,
[ValidateSet('Permission','Input','Configuration','Unhandled','Custom')] [ValidateSet('Permission', 'Input', 'Configuration', 'Unhandled', 'Custom')]
[string]$ExceptionType = 'Unhandled', [string]$ExceptionType = 'Unhandled',
[switch]$Force [switch]$Force
); );

View file

@ -15,35 +15,35 @@ function New-IcingaCheck()
); );
$Check = New-Object -TypeName PSObject; $Check = New-Object -TypeName PSObject;
$Check | Add-Member -membertype NoteProperty -name 'name' -value $Name; $Check | Add-Member -MemberType NoteProperty -Name 'name' -Value $Name;
$Check | Add-Member -membertype NoteProperty -name 'verbose' -value 0; $Check | Add-Member -MemberType NoteProperty -Name 'verbose' -Value 0;
$Check | Add-Member -membertype NoteProperty -name 'messages' -value @(); $Check | Add-Member -MemberType NoteProperty -Name 'messages' -Value @();
$Check | Add-Member -membertype NoteProperty -name 'oks' -value @(); $Check | Add-Member -MemberType NoteProperty -Name 'oks' -Value @();
$Check | Add-Member -membertype NoteProperty -name 'warnings' -value @(); $Check | Add-Member -MemberType NoteProperty -Name 'warnings' -Value @();
$Check | Add-Member -membertype NoteProperty -name 'criticals' -value @(); $Check | Add-Member -MemberType NoteProperty -Name 'criticals' -Value @();
$Check | Add-Member -membertype NoteProperty -name 'unknowns' -value @(); $Check | Add-Member -MemberType NoteProperty -Name 'unknowns' -Value @();
$Check | Add-Member -membertype NoteProperty -name 'okchecks' -value @(); $Check | Add-Member -MemberType NoteProperty -Name 'okchecks' -Value @();
$Check | Add-Member -membertype NoteProperty -name 'warningchecks' -value @(); $Check | Add-Member -MemberType NoteProperty -Name 'warningchecks' -Value @();
$Check | Add-Member -membertype NoteProperty -name 'criticalchecks' -value @(); $Check | Add-Member -MemberType NoteProperty -Name 'criticalchecks' -Value @();
$Check | Add-Member -membertype NoteProperty -name 'unknownchecks' -value @(); $Check | Add-Member -MemberType NoteProperty -Name 'unknownchecks' -Value @();
$Check | Add-Member -membertype NoteProperty -name 'value' -value $Value; $Check | Add-Member -MemberType NoteProperty -Name 'value' -Value $Value;
$Check | Add-Member -membertype NoteProperty -name 'exitcode' -value -1; $Check | Add-Member -MemberType NoteProperty -Name 'exitcode' -Value -1;
$Check | Add-Member -membertype NoteProperty -name 'unit' -value $Unit; $Check | Add-Member -MemberType NoteProperty -Name 'unit' -Value $Unit;
$Check | Add-Member -membertype NoteProperty -name 'spacing' -value 0; $Check | Add-Member -MemberType NoteProperty -Name 'spacing' -Value 0;
$Check | Add-Member -membertype NoteProperty -name 'compiled' -value $FALSE; $Check | Add-Member -MemberType NoteProperty -Name 'compiled' -Value $FALSE;
$Check | Add-Member -membertype NoteProperty -name 'perfdata' -value (-Not $NoPerfData); $Check | Add-Member -MemberType NoteProperty -Name 'perfdata' -Value (-Not $NoPerfData);
$Check | Add-Member -membertype NoteProperty -name 'warning' -value ''; $Check | Add-Member -MemberType NoteProperty -Name 'warning' -Value '';
$Check | Add-Member -membertype NoteProperty -name 'critical' -value ''; $Check | Add-Member -MemberType NoteProperty -Name 'critical' -Value '';
$Check | Add-Member -membertype NoteProperty -name 'minimum' -value $Minimum; $Check | Add-Member -MemberType NoteProperty -Name 'minimum' -Value $Minimum;
$Check | Add-Member -membertype NoteProperty -name 'maximum' -value $Maximum; $Check | Add-Member -MemberType NoteProperty -Name 'maximum' -Value $Maximum;
$Check | Add-Member -membertype NoteProperty -name 'objectexists' -value $ObjectExists; $Check | Add-Member -MemberType NoteProperty -Name 'objectexists' -Value $ObjectExists;
$Check | Add-Member -membertype NoteProperty -name 'translation' -value $Translation; $Check | Add-Member -MemberType NoteProperty -Name 'translation' -Value $Translation;
$Check | Add-Member -membertype NoteProperty -name 'checks' -value $null; $Check | Add-Member -MemberType NoteProperty -Name 'checks' -Value $null;
$Check | Add-Member -membertype NoteProperty -name 'completed' -value $FALSE; $Check | Add-Member -MemberType NoteProperty -Name 'completed' -Value $FALSE;
$Check | Add-Member -membertype NoteProperty -name 'checkcommand' -value ''; $Check | Add-Member -MemberType NoteProperty -Name 'checkcommand' -Value '';
$Check | Add-Member -membertype NoteProperty -name 'checkpackage' -value $FALSE; $Check | Add-Member -MemberType NoteProperty -Name 'checkpackage' -Value $FALSE;
$Check | Add-Member -membertype ScriptMethod -name 'HandleDaemon' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'HandleDaemon' -Value {
# Only apply this once the checkcommand is set # Only apply this once the checkcommand is set
if ([string]::IsNullOrEmpty($this.checkcommand) -Or $global:IcingaDaemonData.FrameworkRunningAsDaemon -eq $FALSE) { if ([string]::IsNullOrEmpty($this.checkcommand) -Or $global:IcingaDaemonData.FrameworkRunningAsDaemon -eq $FALSE) {
return; return;
@ -71,30 +71,30 @@ function New-IcingaCheck()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'AddSpacing' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'AddSpacing' -Value {
$this.spacing += 1; $this.spacing += 1;
} }
$Check | Add-Member -membertype ScriptMethod -name 'AssignCheckCommand' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'AssignCheckCommand' -Value {
param($CheckCommand); param($CheckCommand);
$this.checkcommand = $CheckCommand; $this.checkcommand = $CheckCommand;
$this.HandleDaemon(); $this.HandleDaemon();
} }
$Check | Add-Member -membertype ScriptMethod -name 'GetWarnings' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'GetWarnings' -Value {
return $this.warningchecks; return $this.warningchecks;
} }
$Check | Add-Member -membertype ScriptMethod -name 'GetCriticals' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'GetCriticals' -Value {
return $this.criticalchecks; return $this.criticalchecks;
} }
$Check | Add-Member -membertype ScriptMethod -name 'GetUnknowns' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'GetUnknowns' -Value {
return $this.unknownchecks; return $this.unknownchecks;
} }
$Check | Add-Member -membertype ScriptMethod -name 'SetUnknown' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'SetUnknown' -Value {
$this.AddInternalCheckMessage( $this.AddInternalCheckMessage(
$IcingaEnums.IcingaExitCode.Unknown, $IcingaEnums.IcingaExitCode.Unknown,
$null, $null,
@ -104,7 +104,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'SetWarning' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'SetWarning' -Value {
$this.AddInternalCheckMessage( $this.AddInternalCheckMessage(
$IcingaEnums.IcingaExitCode.Warning, $IcingaEnums.IcingaExitCode.Warning,
$null, $null,
@ -114,7 +114,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'WarnOutOfRange' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WarnOutOfRange' -Value {
param($warning); param($warning);
if ([string]::IsNullOrEmpty($warning)) { if ([string]::IsNullOrEmpty($warning)) {
@ -156,7 +156,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'WarnIfLike' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WarnIfLike' -Value {
param($warning); param($warning);
if ($this.value -Like $warning) { if ($this.value -Like $warning) {
@ -172,7 +172,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'WarnIfNotLike' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WarnIfNotLike' -Value {
param($warning); param($warning);
if (-Not ($this.value -Like $warning)) { if (-Not ($this.value -Like $warning)) {
@ -188,7 +188,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'WarnIfMatch' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WarnIfMatch' -Value {
param($warning); param($warning);
if ($this.value -eq $warning) { if ($this.value -eq $warning) {
@ -204,7 +204,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'WarnIfNotMatch' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WarnIfNotMatch' -Value {
param($warning); param($warning);
if ($this.value -ne $warning) { if ($this.value -ne $warning) {
@ -220,7 +220,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'WarnIfBetweenAndEqual' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WarnIfBetweenAndEqual' -Value {
param($min, $max); param($min, $max);
if ($this.value -ge $min -And $this.value -le $max) { if ($this.value -ge $min -And $this.value -le $max) {
@ -236,7 +236,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'WarnIfBetween' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WarnIfBetween' -Value {
param($min, $max); param($min, $max);
if ($this.value -gt $min -And $this.value -lt $max) { if ($this.value -gt $min -And $this.value -lt $max) {
@ -252,7 +252,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'WarnIfLowerThan' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WarnIfLowerThan' -Value {
param($warning); param($warning);
if ($this.value -lt $warning) { if ($this.value -lt $warning) {
@ -268,7 +268,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'WarnIfLowerEqualThan' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WarnIfLowerEqualThan' -Value {
param($warning); param($warning);
if ($this.value -le $warning) { if ($this.value -le $warning) {
@ -284,7 +284,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'WarnIfGreaterThan' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WarnIfGreaterThan' -Value {
param($warning); param($warning);
if ($this.value -gt $warning) { if ($this.value -gt $warning) {
@ -300,7 +300,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'WarnIfGreaterEqualThan' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WarnIfGreaterEqualThan' -Value {
param($warning); param($warning);
if ($this.value -ge $warning) { if ($this.value -ge $warning) {
@ -316,7 +316,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'SetCritical' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'SetCritical' -Value {
$this.AddInternalCheckMessage( $this.AddInternalCheckMessage(
$IcingaEnums.IcingaExitCode.Critical, $IcingaEnums.IcingaExitCode.Critical,
$null, $null,
@ -326,7 +326,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CritOutOfRange' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CritOutOfRange' -Value {
param($critical); param($critical);
if ([string]::IsNullOrEmpty($critical)) { if ([string]::IsNullOrEmpty($critical)) {
@ -368,7 +368,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CritIfLike' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CritIfLike' -Value {
param($critical); param($critical);
if ($this.value -Like $critical) { if ($this.value -Like $critical) {
@ -384,7 +384,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CritIfNotLike' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CritIfNotLike' -Value {
param($critical); param($critical);
if (-Not ($this.value -Like $critical)) { if (-Not ($this.value -Like $critical)) {
@ -400,7 +400,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CritIfMatch' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CritIfMatch' -Value {
param($critical); param($critical);
if ($this.value -eq $critical) { if ($this.value -eq $critical) {
@ -416,7 +416,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CritIfNotMatch' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CritIfNotMatch' -Value {
param($critical); param($critical);
if ($this.value -ne $critical) { if ($this.value -ne $critical) {
@ -432,7 +432,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CritIfBetweenAndEqual' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CritIfBetweenAndEqual' -Value {
param($min, $max); param($min, $max);
if ($this.value -ge $min -And $this.value -le $max) { if ($this.value -ge $min -And $this.value -le $max) {
@ -448,7 +448,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CritIfBetween' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CritIfBetween' -Value {
param($min, $max); param($min, $max);
if ($this.value -gt $min -And $this.value -lt $max) { if ($this.value -gt $min -And $this.value -lt $max) {
@ -464,7 +464,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CritIfLowerThan' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CritIfLowerThan' -Value {
param($critical); param($critical);
if ($this.value -lt $critical) { if ($this.value -lt $critical) {
@ -480,7 +480,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CritIfLowerEqualThan' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CritIfLowerEqualThan' -Value {
param($critical); param($critical);
if ($this.value -le $critical) { if ($this.value -le $critical) {
@ -496,7 +496,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CritIfGreaterThan' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CritIfGreaterThan' -Value {
param($critical); param($critical);
if ($this.value -gt $critical) { if ($this.value -gt $critical) {
@ -512,7 +512,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CritIfGreaterEqualThan' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CritIfGreaterEqualThan' -Value {
param($critical); param($critical);
if ($this.value -ge $critical) { if ($this.value -ge $critical) {
@ -528,7 +528,7 @@ function New-IcingaCheck()
return $this; return $this;
} }
$Check | Add-Member -membertype ScriptMethod -name 'TranslateValue' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'TranslateValue' -Value {
param($value); param($value);
$value = Format-IcingaPerfDataValue $value; $value = Format-IcingaPerfDataValue $value;
@ -552,14 +552,17 @@ function New-IcingaCheck()
return $value; return $value;
} }
$Check | Add-Member -membertype ScriptMethod -name 'AddInternalCheckMessage' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'AddInternalCheckMessage' -Value {
param($state, $value, $type); param($state, $value, $type);
if ($this.objectexists -ne -1 -And $null -eq $this.objectexists) { if ($this.objectexists -ne -1 -And $null -eq $this.objectexists) {
$this.SetExitCode($IcingaEnums.IcingaExitCode.Unknown); $this.SetExitCode($IcingaEnums.IcingaExitCode.Unknown);
$this.AddMessage([string]::Format( $this.AddMessage(
'{0} does not exist', $this.name [string]::Format(
), $IcingaEnums.IcingaExitCode.Unknown); '{0} does not exist', $this.name
),
$IcingaEnums.IcingaExitCode.Unknown
);
return; return;
} }
@ -596,7 +599,7 @@ function New-IcingaCheck()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'AddMessage' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'AddMessage' -Value {
param($message, [int]$exitcode); param($message, [int]$exitcode);
[string]$outputMessage = [string]::Format( [string]$outputMessage = [string]::Format(
@ -626,7 +629,7 @@ function New-IcingaCheck()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'AddCheckStateArrays' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'AddCheckStateArrays' -Value {
switch ([int]$this.exitcode) { switch ([int]$this.exitcode) {
$IcingaEnums.IcingaExitCode.Ok { $IcingaEnums.IcingaExitCode.Ok {
$this.okchecks += $this.name; $this.okchecks += $this.name;
@ -647,27 +650,27 @@ function New-IcingaCheck()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'PrintOkMessages' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'PrintOkMessages' -Value {
param([string]$spaces); param([string]$spaces);
$this.OutputMessageArray($this.oks, $spaces); $this.OutputMessageArray($this.oks, $spaces);
} }
$Check | Add-Member -membertype ScriptMethod -name 'PrintWarningMessages' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'PrintWarningMessages' -Value {
param([string]$spaces); param([string]$spaces);
$this.OutputMessageArray($this.warnings, $spaces); $this.OutputMessageArray($this.warnings, $spaces);
} }
$Check | Add-Member -membertype ScriptMethod -name 'PrintCriticalMessages' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'PrintCriticalMessages' -Value {
param([string]$spaces); param([string]$spaces);
$this.OutputMessageArray($this.criticals, $spaces); $this.OutputMessageArray($this.criticals, $spaces);
} }
$Check | Add-Member -membertype ScriptMethod -name 'PrintUnknownMessages' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'PrintUnknownMessages' -Value {
param([string]$spaces); param([string]$spaces);
$this.OutputMessageArray($this.unknowns, $spaces); $this.OutputMessageArray($this.unknowns, $spaces);
} }
$Check | Add-Member -membertype ScriptMethod -name 'PrintAllMessages' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'PrintAllMessages' -Value {
[string]$spaces = New-StringTree $this.spacing; [string]$spaces = New-StringTree $this.spacing;
$this.OutputMessageArray($this.unknowns, $spaces); $this.OutputMessageArray($this.unknowns, $spaces);
$this.OutputMessageArray($this.criticals, $spaces); $this.OutputMessageArray($this.criticals, $spaces);
@ -675,7 +678,7 @@ function New-IcingaCheck()
$this.OutputMessageArray($this.oks, $spaces); $this.OutputMessageArray($this.oks, $spaces);
} }
$Check | Add-Member -membertype ScriptMethod -name 'OutputMessageArray' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'OutputMessageArray' -Value {
param($msgArray, [string]$spaces); param($msgArray, [string]$spaces);
foreach ($msg in $msgArray) { foreach ($msg in $msgArray) {
@ -683,7 +686,7 @@ function New-IcingaCheck()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'PrintOutputMessages' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'PrintOutputMessages' -Value {
[string]$spaces = New-StringTree $this.spacing; [string]$spaces = New-StringTree $this.spacing;
if ($this.unknowns.Count -ne 0) { if ($this.unknowns.Count -ne 0) {
$this.PrintUnknownMessages($spaces); $this.PrintUnknownMessages($spaces);
@ -698,7 +701,7 @@ function New-IcingaCheck()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'SetExitCode' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'SetExitCode' -Value {
param([int]$code); param([int]$code);
# Only overwrite the exit code in case our new value is greater then # Only overwrite the exit code in case our new value is greater then
@ -729,23 +732,23 @@ function New-IcingaCheck()
$this.exitcode = $code; $this.exitcode = $code;
} }
$Check | Add-Member -membertype ScriptMethod -name 'ValidateUnit' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'ValidateUnit' -Value {
if ($null -ne $this.unit -And (-Not $IcingaEnums.IcingaMeasurementUnits.ContainsKey($this.unit))) { if ($null -ne $this.unit -And (-Not $IcingaEnums.IcingaMeasurementUnits.ContainsKey($this.unit))) {
$this.AddMessage( $this.AddMessage(
[string]::Format( [string]::Format(
'Error on check "{0}": Usage of invalid plugin unit "{1}". Allowed units are: {2}', 'Error on check "{0}": Usage of invalid plugin unit "{1}". Allowed units are: {2}',
$this.name, $this.name,
$this.unit, $this.unit,
(($IcingaEnums.IcingaMeasurementUnits.Keys | Sort-Object name) -Join ', ') (($IcingaEnums.IcingaMeasurementUnits.Keys | Sort-Object name) -Join ', ')
), ),
$IcingaEnums.IcingaExitCode.Unknown $IcingaEnums.IcingaExitCode.Unknown
) )
$this.unit = ''; $this.unit = '';
$this.exitcode = $IcingaEnums.IcingaExitCode.Unknown; $this.exitcode = $IcingaEnums.IcingaExitCode.Unknown;
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'AddOkOutput' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'AddOkOutput' -Value {
if ([int]$this.exitcode -eq -1) { if ([int]$this.exitcode -eq -1) {
$this.exitcode = $IcingaEnums.IcingaExitCode.Ok; $this.exitcode = $IcingaEnums.IcingaExitCode.Ok;
$this.AddMessage( $this.AddMessage(
@ -760,7 +763,7 @@ function New-IcingaCheck()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'SilentCompile' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'SilentCompile' -Value {
if ($this.compiled) { if ($this.compiled) {
return; return;
} }
@ -770,7 +773,7 @@ function New-IcingaCheck()
$this.AddCheckStateArrays(); $this.AddCheckStateArrays();
} }
$Check | Add-Member -membertype ScriptMethod -name 'Compile' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'Compile' -Value {
param([bool]$Verbose = $FALSE); param([bool]$Verbose = $FALSE);
if ($this.compiled) { if ($this.compiled) {
@ -789,7 +792,7 @@ function New-IcingaCheck()
return $this.exitcode; return $this.exitcode;
} }
$Check | Add-Member -membertype ScriptMethod -name 'GetPerfData' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'GetPerfData' -Value {
if ($this.completed -Or -Not $this.perfdata) { if ($this.completed -Or -Not $this.perfdata) {
return $null; return $null;
@ -818,7 +821,7 @@ function New-IcingaCheck()
return $perfdata; return $perfdata;
} }
$Check | Add-Member -membertype ScriptMethod -name 'AutodiscoverMinMax' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'AutodiscoverMinMax' -Value {
if ([string]::IsNullOrEmpty($this.minimum) -eq $FALSE -Or [string]::IsNullOrEmpty($this.maximum) -eq $FALSE) { if ([string]::IsNullOrEmpty($this.minimum) -eq $FALSE -Or [string]::IsNullOrEmpty($this.maximum) -eq $FALSE) {
return; return;
} }

View file

@ -16,27 +16,27 @@ function New-IcingaCheckPackage()
); );
$Check = New-Object -TypeName PSObject; $Check = New-Object -TypeName PSObject;
$Check | Add-Member -membertype NoteProperty -name 'name' -value $Name; $Check | Add-Member -MemberType NoteProperty -Name 'name' -Value $Name;
$Check | Add-Member -membertype NoteProperty -name 'exitcode' -value -1; $Check | Add-Member -MemberType NoteProperty -Name 'exitcode' -Value -1;
$Check | Add-Member -membertype NoteProperty -name 'verbose' -value $Verbose; $Check | Add-Member -MemberType NoteProperty -Name 'verbose' -Value $Verbose;
$Check | Add-Member -membertype NoteProperty -name 'hidden' -value $Hidden; $Check | Add-Member -MemberType NoteProperty -Name 'hidden' -Value $Hidden;
$Check | Add-Member -membertype NoteProperty -name 'checks' -value $Checks; $Check | Add-Member -MemberType NoteProperty -Name 'checks' -Value $Checks;
$Check | Add-Member -membertype NoteProperty -name 'opand' -value $OperatorAnd; $Check | Add-Member -MemberType NoteProperty -Name 'opand' -Value $OperatorAnd;
$Check | Add-Member -membertype NoteProperty -name 'opor' -value $OperatorOr; $Check | Add-Member -MemberType NoteProperty -Name 'opor' -Value $OperatorOr;
$Check | Add-Member -membertype NoteProperty -name 'opnone' -value $OperatorNone; $Check | Add-Member -MemberType NoteProperty -Name 'opnone' -Value $OperatorNone;
$Check | Add-Member -membertype NoteProperty -name 'opmin' -value $OperatorMin; $Check | Add-Member -MemberType NoteProperty -Name 'opmin' -Value $OperatorMin;
$Check | Add-Member -membertype NoteProperty -name 'opmax' -value $OperatorMax; $Check | Add-Member -MemberType NoteProperty -Name 'opmax' -Value $OperatorMax;
$Check | Add-Member -membertype NoteProperty -name 'spacing' -value 0; $Check | Add-Member -MemberType NoteProperty -Name 'spacing' -Value 0;
$Check | Add-Member -membertype NoteProperty -name 'compiled' -value $FALSE; $Check | Add-Member -MemberType NoteProperty -Name 'compiled' -Value $FALSE;
$Check | Add-Member -membertype NoteProperty -name 'perfdata' -value $FALSE; $Check | Add-Member -MemberType NoteProperty -Name 'perfdata' -Value $FALSE;
$Check | Add-Member -membertype NoteProperty -name 'checkcommand' -value ''; $Check | Add-Member -MemberType NoteProperty -Name 'checkcommand' -Value '';
$Check | Add-Member -membertype NoteProperty -name 'headermsg' -value ''; $Check | Add-Member -MemberType NoteProperty -Name 'headermsg' -Value '';
$Check | Add-Member -membertype NoteProperty -name 'checkpackage' -value $TRUE; $Check | Add-Member -MemberType NoteProperty -Name 'checkpackage' -Value $TRUE;
$Check | Add-Member -membertype NoteProperty -name 'warningchecks' -value @(); $Check | Add-Member -MemberType NoteProperty -Name 'warningchecks' -Value @();
$Check | Add-Member -membertype NoteProperty -name 'criticalchecks' -value @(); $Check | Add-Member -MemberType NoteProperty -Name 'criticalchecks' -Value @();
$Check | Add-Member -membertype NoteProperty -name 'unknownchecks' -value @(); $Check | Add-Member -MemberType NoteProperty -Name 'unknownchecks' -Value @();
$Check | Add-Member -membertype ScriptMethod -name 'HasChecks' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'HasChecks' -Value {
if ($this.checks -ne 0) { if ($this.checks -ne 0) {
return $TRUE return $TRUE
} }
@ -44,13 +44,13 @@ function New-IcingaCheckPackage()
return $FALSE; return $FALSE;
} }
$Check | Add-Member -membertype ScriptMethod -name 'Initialise' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'Initialise' -Value {
foreach ($check in $this.checks) { foreach ($check in $this.checks) {
$this.InitCheck($check); $this.InitCheck($check);
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'InitCheck' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'InitCheck' -Value {
param($check); param($check);
if ($null -eq $check) { if ($null -eq $check) {
@ -62,7 +62,7 @@ function New-IcingaCheckPackage()
$check.SilentCompile(); $check.SilentCompile();
} }
$Check | Add-Member -membertype ScriptMethod -name 'AddSpacing' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'AddSpacing' -Value {
$this.spacing += 1; $this.spacing += 1;
foreach ($check in $this.checks) { foreach ($check in $this.checks) {
$check.spacing = $this.spacing; $check.spacing = $this.spacing;
@ -70,7 +70,7 @@ function New-IcingaCheckPackage()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'AddCheck' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'AddCheck' -Value {
param($check); param($check);
if ($null -eq $check) { if ($null -eq $check) {
@ -81,7 +81,7 @@ function New-IcingaCheckPackage()
$this.checks += $check; $this.checks += $check;
} }
$Check | Add-Member -membertype ScriptMethod -name 'GetWarnings' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'GetWarnings' -Value {
foreach ($check in $this.checks) { foreach ($check in $this.checks) {
$this.warningchecks += $check.GetWarnings(); $this.warningchecks += $check.GetWarnings();
} }
@ -89,7 +89,7 @@ function New-IcingaCheckPackage()
return $this.warningchecks; return $this.warningchecks;
} }
$Check | Add-Member -membertype ScriptMethod -name 'GetCriticals' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'GetCriticals' -Value {
foreach ($check in $this.checks) { foreach ($check in $this.checks) {
$this.criticalchecks += $check.GetCriticals(); $this.criticalchecks += $check.GetCriticals();
} }
@ -97,7 +97,7 @@ function New-IcingaCheckPackage()
return $this.criticalchecks; return $this.criticalchecks;
} }
$Check | Add-Member -membertype ScriptMethod -name 'GetUnknowns' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'GetUnknowns' -Value {
foreach ($check in $this.checks) { foreach ($check in $this.checks) {
$this.unknownchecks += $check.GetUnknowns(); $this.unknownchecks += $check.GetUnknowns();
} }
@ -105,7 +105,7 @@ function New-IcingaCheckPackage()
return $this.unknownchecks; return $this.unknownchecks;
} }
$Check | Add-Member -membertype ScriptMethod -name 'AssignCheckCommand' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'AssignCheckCommand' -Value {
param($CheckCommand); param($CheckCommand);
$this.checkcommand = $CheckCommand; $this.checkcommand = $CheckCommand;
@ -115,7 +115,7 @@ function New-IcingaCheckPackage()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'Compile' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'Compile' -Value {
param([bool]$Verbose); param([bool]$Verbose);
if ($this.compiled) { if ($this.compiled) {
@ -129,24 +129,24 @@ function New-IcingaCheckPackage()
if ($this.CheckAllOk() -eq $FALSE) { if ($this.CheckAllOk() -eq $FALSE) {
$this.GetWorstExitCode(); $this.GetWorstExitCode();
} }
} elseif($this.opor) { } elseif ($this.opor) {
if ($this.CheckOneOk() -eq $FALSE) { if ($this.CheckOneOk() -eq $FALSE) {
$this.GetWorstExitCode(); $this.GetWorstExitCode();
} }
} elseif($this.opnone) { } elseif ($this.opnone) {
if ($this.CheckOneOk() -eq $TRUE) { if ($this.CheckOneOk() -eq $TRUE) {
$this.GetWorstExitCode(); $this.GetWorstExitCode();
$this.exitcode = $IcingaEnums.IcingaExitCode.Critical; $this.exitcode = $IcingaEnums.IcingaExitCode.Critical;
} else { } else {
$this.exitcode = $IcingaEnums.IcingaExitCode.Ok; $this.exitcode = $IcingaEnums.IcingaExitCode.Ok;
} }
} elseif([int]$this.opmin -ne -1) { } elseif ([int]$this.opmin -ne -1) {
if ($this.CheckMinimumOk() -eq $FALSE) { if ($this.CheckMinimumOk() -eq $FALSE) {
$this.GetWorstExitCode(); $this.GetWorstExitCode();
} else { } else {
$this.exitcode = $IcingaEnums.IcingaExitCode.Ok; $this.exitcode = $IcingaEnums.IcingaExitCode.Ok;
} }
} elseif([int]$this.opmax -ne -1) { } elseif ([int]$this.opmax -ne -1) {
if ($this.CheckMaximumOk() -eq $FALSE) { if ($this.CheckMaximumOk() -eq $FALSE) {
$this.GetWorstExitCode(); $this.GetWorstExitCode();
} else { } else {
@ -168,11 +168,11 @@ function New-IcingaCheckPackage()
return $this.exitcode; return $this.exitcode;
} }
$Check | Add-Member -membertype ScriptMethod -name 'SilentCompile' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'SilentCompile' -Value {
$this.Compile($FALSE) | Out-Null; $this.Compile($FALSE) | Out-Null;
} }
$Check | Add-Member -membertype ScriptMethod -name 'GetOkCount' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'GetOkCount' -Value {
[int]$okCount = 0; [int]$okCount = 0;
foreach ($check in $this.checks) { foreach ($check in $this.checks) {
if ([int]$check.exitcode -eq [int]$IcingaEnums.IcingaExitCode.Ok) { if ([int]$check.exitcode -eq [int]$IcingaEnums.IcingaExitCode.Ok) {
@ -183,12 +183,14 @@ function New-IcingaCheckPackage()
return $okCount; return $okCount;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CheckMinimumOk' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CheckMinimumOk' -Value {
if ($this.opmin -gt $this.checks.Count) { if ($this.opmin -gt $this.checks.Count) {
Write-IcingaPluginOutput ([string]::Format( Write-IcingaPluginOutput (
'Unknown: The minimum argument ({0}) is exceeding the amount of assigned checks ({1}) to this package "{2}"', [string]::Format(
$this.opmin, $this.checks.Count, $this.name 'Unknown: The minimum argument ({0}) is exceeding the amount of assigned checks ({1}) to this package "{2}"',
)); $this.opmin, $this.checks.Count, $this.name
)
);
$this.exitcode = $IcingaEnums.IcingaExitCode.Unknown; $this.exitcode = $IcingaEnums.IcingaExitCode.Unknown;
return $FALSE; return $FALSE;
} }
@ -202,12 +204,14 @@ function New-IcingaCheckPackage()
return $FALSE; return $FALSE;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CheckMaximumOk' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CheckMaximumOk' -Value {
if ($this.opmax -gt $this.checks.Count) { if ($this.opmax -gt $this.checks.Count) {
Write-IcingaPluginOutput ([string]::Format( Write-IcingaPluginOutput (
'Unknown: The maximum argument ({0}) is exceeding the amount of assigned checks ({1}) to this package "{2}"', [string]::Format(
$this.opmax, $this.checks.Count, $this.name 'Unknown: The maximum argument ({0}) is exceeding the amount of assigned checks ({1}) to this package "{2}"',
)); $this.opmax, $this.checks.Count, $this.name
)
);
$this.exitcode = $IcingaEnums.IcingaExitCode.Unknown; $this.exitcode = $IcingaEnums.IcingaExitCode.Unknown;
return $FALSE; return $FALSE;
} }
@ -221,7 +225,7 @@ function New-IcingaCheckPackage()
return $FALSE; return $FALSE;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CheckAllOk' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CheckAllOk' -Value {
foreach ($check in $this.checks) { foreach ($check in $this.checks) {
if ([int]$check.exitcode -ne [int]$IcingaEnums.IcingaExitCode.Ok) { if ([int]$check.exitcode -ne [int]$IcingaEnums.IcingaExitCode.Ok) {
return $FALSE; return $FALSE;
@ -231,7 +235,7 @@ function New-IcingaCheckPackage()
return $TRUE; return $TRUE;
} }
$Check | Add-Member -membertype ScriptMethod -name 'CheckOneOk' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'CheckOneOk' -Value {
foreach ($check in $this.checks) { foreach ($check in $this.checks) {
if ([int]$check.exitcode -eq [int]$IcingaEnums.IcingaExitCode.Ok) { if ([int]$check.exitcode -eq [int]$IcingaEnums.IcingaExitCode.Ok) {
$this.exitcode = $check.exitcode; $this.exitcode = $check.exitcode;
@ -242,7 +246,7 @@ function New-IcingaCheckPackage()
return $FALSE; return $FALSE;
} }
$Check | Add-Member -membertype ScriptMethod -name 'GetPackageConfigMessage' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'GetPackageConfigMessage' -Value {
if ($this.opand) { if ($this.opand) {
return 'Match All'; return 'Match All';
} elseif ($this.opor) { } elseif ($this.opor) {
@ -256,7 +260,7 @@ function New-IcingaCheckPackage()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'PrintOutputMessageSorted' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'PrintOutputMessageSorted' -Value {
param($skipHidden, $skipExitCode); param($skipHidden, $skipExitCode);
if ($this.hidden -And $skipHidden) { if ($this.hidden -And $skipHidden) {
@ -291,20 +295,20 @@ function New-IcingaCheckPackage()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'WriteAllOutput' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WriteAllOutput' -Value {
$this.PrintOutputMessageSorted($TRUE, -1); $this.PrintOutputMessageSorted($TRUE, -1);
} }
$Check | Add-Member -membertype ScriptMethod -name 'PrintAllMessages' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'PrintAllMessages' -Value {
$this.WritePackageOutputStatus(); $this.WritePackageOutputStatus();
$this.WriteAllOutput(); $this.WriteAllOutput();
} }
$Check | Add-Member -membertype ScriptMethod -name 'WriteCheckErrors' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WriteCheckErrors' -Value {
$this.PrintOutputMessageSorted($FALSE, $IcingaEnums.IcingaExitCode.Ok); $this.PrintOutputMessageSorted($FALSE, $IcingaEnums.IcingaExitCode.Ok);
} }
$Check | Add-Member -membertype ScriptMethod -name 'PrintNoChecksConfigured' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'PrintNoChecksConfigured' -Value {
if ($this.checks.Count -eq 0) { if ($this.checks.Count -eq 0) {
Write-IcingaPluginOutput ( Write-IcingaPluginOutput (
[string]::Format( [string]::Format(
@ -318,7 +322,7 @@ function New-IcingaCheckPackage()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'WritePackageOutputStatus' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'WritePackageOutputStatus' -Value {
if ($this.hidden) { if ($this.hidden) {
return; return;
} }
@ -344,7 +348,7 @@ function New-IcingaCheckPackage()
); );
} }
$Check | Add-Member -membertype ScriptMethod -name 'PrintOutputMessages' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'PrintOutputMessages' -Value {
[bool]$printAll = $FALSE; [bool]$printAll = $FALSE;
switch ($this.verbose) { switch ($this.verbose) {
@ -375,7 +379,7 @@ function New-IcingaCheckPackage()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'AddUniqueSortedChecksToHeader' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'AddUniqueSortedChecksToHeader' -Value {
param($checkarray, $state); param($checkarray, $state);
[hashtable]$CheckHash = @{}; [hashtable]$CheckHash = @{};
@ -397,7 +401,7 @@ function New-IcingaCheckPackage()
} }
} }
$Check | Add-Member -membertype ScriptMethod -name 'GetWorstExitCode' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'GetWorstExitCode' -Value {
if ([int]$this.exitcode -eq [int]$IcingaEnums.IcingaExitCode.Unknown) { if ([int]$this.exitcode -eq [int]$IcingaEnums.IcingaExitCode.Unknown) {
return; return;
} }
@ -428,7 +432,7 @@ function New-IcingaCheckPackage()
); );
} }
$Check | Add-Member -membertype ScriptMethod -name 'GetPerfData' -value { $Check | Add-Member -MemberType ScriptMethod -Name 'GetPerfData' -Value {
[string]$perfData = ''; [string]$perfData = '';
[hashtable]$CollectedPerfData = @{}; [hashtable]$CollectedPerfData = @{};

View file

@ -9,10 +9,10 @@ function New-IcingaCheckresult()
); );
$CheckResult = New-Object -TypeName PSObject; $CheckResult = New-Object -TypeName PSObject;
$CheckResult | Add-Member -membertype NoteProperty -name 'check' -value $Check; $CheckResult | Add-Member -MemberType NoteProperty -Name 'check' -Value $Check;
$CheckResult | Add-Member -membertype NoteProperty -name 'noperfdata' -value $NoPerfData; $CheckResult | Add-Member -MemberType NoteProperty -Name 'noperfdata' -Value $NoPerfData;
$CheckResult | Add-Member -membertype ScriptMethod -name 'Compile' -value { $CheckResult | Add-Member -MemberType ScriptMethod -Name 'Compile' -Value {
if ($null -eq $this.check) { if ($null -eq $this.check) {
return $IcingaEnums.IcingaExitCode.Unknown; return $IcingaEnums.IcingaExitCode.Unknown;
} }

View file

@ -30,14 +30,16 @@ function New-IcingaPerformanceDataEntry()
$maximum = [string]::Format(';{0}', $PerfDataObject.maximum); $maximum = [string]::Format(';{0}', $PerfDataObject.maximum);
} }
return ([string]::Format( return (
"'{0}'={1}{2};{3};{4}{5}{6} ", [string]::Format(
$LabelName.ToLower(), "'{0}'={1}{2};{3};{4}{5}{6} ",
(Format-IcingaPerfDataValue $PerfValue), $LabelName.ToLower(),
$PerfDataObject.unit, (Format-IcingaPerfDataValue $PerfValue),
(Format-IcingaPerfDataValue $PerfDataObject.warning), $PerfDataObject.unit,
(Format-IcingaPerfDataValue $PerfDataObject.critical), (Format-IcingaPerfDataValue $PerfDataObject.warning),
(Format-IcingaPerfDataValue $minimum), (Format-IcingaPerfDataValue $PerfDataObject.critical),
(Format-IcingaPerfDataValue $maximum) (Format-IcingaPerfDataValue $minimum),
)); (Format-IcingaPerfDataValue $maximum)
)
);
} }

View file

@ -59,11 +59,9 @@ function Convert-Base64ToCredentials()
); );
$Credentials.Add( $Credentials.Add(
'password', 'password',
(ConvertTo-IcingaSecureString ` (
$AuthString.Substring( ConvertTo-IcingaSecureString `
$AuthString.IndexOf(':') + 1, $AuthString.Substring($AuthString.IndexOf(':') + 1, $AuthString.Length - $UserData.Length - 1)
$AuthString.Length - $UserData.Length - 1
)
) )
); );
@ -77,8 +75,8 @@ function Convert-Base64ToCredentials()
$Credentials.Add('domain', $AuthData[0]); $Credentials.Add('domain', $AuthData[0]);
$Credentials.Add( $Credentials.Add(
'user', 'user',
(ConvertTo-IcingaSecureString ` (
$AuthData[1] ConvertTo-IcingaSecureString $AuthData[1]
) )
); );
$AuthData = $null; $AuthData = $null;
@ -86,8 +84,8 @@ function Convert-Base64ToCredentials()
$Credentials.Add('domain', $null); $Credentials.Add('domain', $null);
$Credentials.Add( $Credentials.Add(
'user', 'user',
(ConvertTo-IcingaSecureString ` (
$UserData ConvertTo-IcingaSecureString $UserData
) )
); );
} }

View file

@ -3,7 +3,7 @@ function Enable-IcingaUntrustedCertificateValidation()
try { try {
# There is no other way as to use C# for this specific # There is no other way as to use C# for this specific
# case to configure the certificate validation check # case to configure the certificate validation check
add-type @" Add-Type @"
using System.Net; using System.Net;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;

View file

@ -23,10 +23,12 @@ function Get-IcingaSSLCertForSocket()
# Windows cert store. Try to look it up an return it if # Windows cert store. Try to look it up an return it if
# it is found # it is found
if ([string]::IsNullOrEmpty($CertThumbprint) -eq $FALSE) { if ([string]::IsNullOrEmpty($CertThumbprint) -eq $FALSE) {
$Certificates = Get-ChildItem -Path 'cert:\*' -Recurse ` $Certificates = Get-ChildItem `
-Include $CertThumbprint ` -Path 'cert:\*' `
-ErrorAction SilentlyContinue ` -Recurse `
-WarningAction SilentlyContinue; -Include $CertThumbprint `
-ErrorAction SilentlyContinue `
-WarningAction SilentlyContinue;
if ($Certificates.Count -ne 0) { if ($Certificates.Count -ne 0) {
return $Certificates[0]; return $Certificates[0];

View file

@ -39,7 +39,7 @@ function Read-IcingaRESTMessage()
# Arguments # Arguments
$ArgumentsSplit = $Arguments.Split('&'); $ArgumentsSplit = $Arguments.Split('&');
$ArgumentsSplit+='\\\\\\\\\\\\=FIN'; $ArgumentsSplit+='\\\\\\\\\\\\=FIN';
foreach ( $Argument in $ArgumentsSplit | Sort-Object -descending) { foreach ( $Argument in $ArgumentsSplit | Sort-Object -Descending) {
if ($Argument.Contains('=')) { if ($Argument.Contains('=')) {
$Argument -match '(.+)=(.+)' | Out-Null; $Argument -match '(.+)=(.+)' | Out-Null;
If (($Matches[1] -ne $Current) -And ($NULL -ne $Current)) { If (($Matches[1] -ne $Current) -And ($NULL -ne $Current)) {
@ -58,7 +58,7 @@ function Read-IcingaRESTMessage()
$SplitString = $RestMessage.split("`r`n"); $SplitString = $RestMessage.split("`r`n");
foreach ( $SingleString in $SplitString ) { foreach ( $SingleString in $SplitString ) {
if ( ([string]::IsNullOrEmpty($SingleString) -eq $FALSE) -And ($SingleString -match '^{.+' -eq $FALSE) ) { if ( ([string]::IsNullOrEmpty($SingleString) -eq $FALSE) -And ($SingleString -match '^{.+' -eq $FALSE) ) {
$SingleSplitString = $SingleString.Split(':',2); $SingleSplitString = $SingleString.Split(':', 2);
$Request.Header.Add( $SingleSplitString[0], $SingleSplitString[1].Trim()); $Request.Header.Add( $SingleSplitString[0], $SingleSplitString[1].Trim());
} }
} }

View file

@ -1,3 +1,4 @@
<# <#
.SYNOPSIS .SYNOPSIS
Tests provided credentials against either the local machine or a domain controller Tests provided credentials against either the local machine or a domain controller
@ -37,7 +38,7 @@ function Test-IcingaRESTCredentials()
[string]$AuthMethod = [System.DirectoryServices.AccountManagement.ContextType]::Machine; [string]$AuthMethod = [System.DirectoryServices.AccountManagement.ContextType]::Machine;
[string]$AuthDomain = $env:COMPUTERNAME; [string]$AuthDomain = $env:COMPUTERNAME;
# If we specify a domain, we should authenticate against our Domain # If we specify a domain, we should authenticate against our Domain
if ([string]::IsNullOrEmpty($Domain) -eq $FALSE) { if ([string]::IsNullOrEmpty($Domain) -eq $FALSE) {
$AuthMethod = [System.DirectoryServices.AccountManagement.ContextType]::Domain; $AuthMethod = [System.DirectoryServices.AccountManagement.ContextType]::Domain;
$AuthDomain = $Domain; $AuthDomain = $Domain;
@ -63,9 +64,10 @@ function Test-IcingaRESTCredentials()
try { try {
# Try to authenticate and either return true or false as integer # Try to authenticate and either return true or false as integer
[bool]$AuthResult = [int]($AccountService.ValidateCredentials( [bool]$AuthResult = [int]($AccountService.ValidateCredentials(
(ConvertFrom-IcingaSecureString $UserName), (ConvertFrom-IcingaSecureString $UserName),
(ConvertFrom-IcingaSecureString $Password) (ConvertFrom-IcingaSecureString $Password)
)); )
);
return $AuthResult; return $AuthResult;
} catch { } catch {