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
Will fetch the ticket for certificate signing by using the Icinga Director
Self-Service API
Will fetch the ticket for certificate signing by using the Icinga Director
Self-Service API
.DESCRIPTION
Use the Self-Service API of the Icinga Director to connect to it and fetch the
ticket to sign Icinga 2 certificate requests
Use the Self-Service API of the Icinga Director to connect to it and fetch the
ticket to sign Icinga 2 certificate requests
.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
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
The URL pointing directly to the Icinga Web 2 Director module
The URL pointing directly to the Icinga Web 2 Director module
.PARAMETER ApiKey
The host key to authenticate against the Self-Service API
The host key to authenticate against the Self-Service API
.INPUTS
System.String
System.String
.OUTPUTS
System.Object
System.Object
.LINK
https://github.com/Icinga/icinga-powershell-framework
https://github.com/Icinga/icinga-powershell-framework
#>
function Get-IcingaDirectorSelfServiceTicket()
{
param(
$DirectorUrl,
$ApiKey = $null
);
param (
$DirectorUrl,
$ApiKey = $null
);
if ([string]::IsNullOrEmpty($DirectorUrl)) {
Write-IcingaConsoleError 'Unable to fetch host ticket. No Director url has been specified';
return;
}
if ([string]::IsNullOrEmpty($DirectorUrl)) {
Write-IcingaConsoleError 'Unable to fetch host ticket. No Director url has been specified';
return;
}
if ([string]::IsNullOrEmpty($ApiKey)) {
Write-IcingaConsoleError 'Unable to fetch host ticket. No API key has been specified';
return;
}
if ([string]::IsNullOrEmpty($ApiKey)) {
Write-IcingaConsoleError 'Unable to fetch host ticket. No API key has been specified';
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) {
throw $response.Content;
}
if ($response.StatusCode -ne 200) {
throw $response.Content;
}
$JsonContent = ConvertFrom-Json -InputObject $response.Content;
$JsonContent = ConvertFrom-Json -InputObject $response.Content;
return $JsonContent;
return $JsonContent;
}

View file

@ -10,7 +10,7 @@
.PARAMETER ConfigObject
The custom config object to check for
.PARAMETER ConfigKey
The key which is checked
The key which is checked
.INPUTS
System.String
.OUTPUTS

View file

@ -1,27 +1,27 @@
<#
.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
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
or to build data tables over time
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
or to build data tables over time
.FUNCTIONALITY
Returns cached data for specific content
Returns cached data for specific content
.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
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
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
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
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
.INPUTS
System.String
System.String
.OUTPUTS
System.Object
System.Object
.LINK
https://github.com/Icinga/icinga-powershell-framework
https://github.com/Icinga/icinga-powershell-framework
.NOTES
#>
function Get-IcingaCacheData()
@ -39,7 +39,7 @@ function Get-IcingaCacheData()
if ((Test-Path $CacheFile) -eq $FALSE) {
return $null;
}
$Content = Get-Content -Path $CacheFile;
if ([string]::IsNullOrEmpty($Content)) {

View file

@ -1,27 +1,27 @@
<#
.SYNOPSIS
Writes data to a cache file for the Framework
Writes data to a cache file for the Framework
.DESCRIPTION
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
or to build data tables over time
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
or to build data tables over time
.FUNCTIONALITY
Writes data for specific value to a cache file
Writes data for specific value to a cache file
.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
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
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
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
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
.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
System.String
System.String
.LINK
https://github.com/Icinga/icinga-powershell-framework
https://github.com/Icinga/icinga-powershell-framework
.NOTES
#>
@ -61,7 +61,7 @@ function Set-IcingaCacheData()
}
try {
Set-Content -Path $CacheFile -Value (ConvertTo-Json -InputObject $cacheData -Depth 100) | Out-Null;
Set-Content -Path $CacheFile -Value (ConvertTo-Json -InputObject $cacheData -Depth 100) | Out-Null;
} catch {
Exit-IcingaThrowException -InputString $_.Exception -CustomMessage (Get-IcingaCacheDir) -StringPattern 'System.UnauthorizedAccessException' -ExceptionType 'Permission' -ExceptionThrown $IcingaExceptions.Permission.CacheFolder;
Exit-IcingaThrowException -CustomMessage $_.Exception -ExceptionType 'Unhandled' -Force;

View file

@ -35,6 +35,6 @@ function Get-IcingaCheckSchedulerPluginOutput()
$CheckResult = [string]::Join("`r`n", $IcingaDaemonData.IcingaThreadContent.Scheduler.PluginCache);
$IcingaDaemonData.IcingaThreadContent.Scheduler.PluginCache = @();
return $CheckResult;
}

View file

@ -16,7 +16,7 @@
function Get-IcingaFrameworkDebugMode()
{
$DebugMode = Get-IcingaPowerShellConfig -Path 'Framework.DebugMode';
if ($null -eq $DebugMode) {
return $FALSE;
}

View file

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

View file

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

View file

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

View file

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

View file

@ -31,7 +31,6 @@ function Restart-IcingaService()
Restart-Service "$Service";
} -Args $Service;
} else {
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.Start();
Add-IcingaHashtableItem -Key $Name -Value ([hashtable]::Synchronized(
@{
'Active' = $TRUE;
'Timer' = $TimerObject;
}
)) -Hashtable $global:IcingaDaemonData.IcingaTimers -Override | Out-Null;
Add-IcingaHashtableItem -Key $Name -Value (
[hashtable]::Synchronized(
@{
'Active' = $TRUE;
'Timer' = $TimerObject;
}
)
) -Hashtable $global:IcingaDaemonData.IcingaTimers -Override | Out-Null;
}

View file

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

View file

@ -37,7 +37,7 @@ function Test-IcingaZipBinaryChecksum()
$MD5Checksum = ($MD5Checksum.Split(' ')[0]).ToLower();
$FileHash = ((Get-FileHash $Path -Algorithm MD5).Hash).ToLower();
if ($MD5Checksum -ne $FileHash) {
return $FALSE;
}

View file

@ -32,5 +32,5 @@ function Unblock-IcingaPowerShellFiles()
}
Write-IcingaConsoleNotice 'Unblocking Icinga PowerShell Files';
Get-ChildItem -Path $Path -Recurse | Unblock-File;
Get-ChildItem -Path $Path -Recurse | Unblock-File;
}

View file

@ -24,7 +24,7 @@ function Enable-IcingaFirewall()
'Inbound Firewall Rule to allow Icinga 2 masters / satellites to connect to the Icinga 2 Agent installed on this system.',
$IcingaPort
);
$FirewallResult = Start-IcingaProcess -Executable 'netsh' -Arguments $FirewallRule;
if ($FirewallResult.ExitCode -ne 0) {

View file

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

View file

@ -18,7 +18,7 @@ function Get-IcingaAgentHostCertificate()
}
$Certificate = New-Object Security.Cryptography.X509Certificates.X509Certificate2 $CertPath;
return @{
'CertFile' = $CertPath;
'Subject' = $Certificate.Subject;

View file

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

View file

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

View file

@ -68,8 +68,8 @@ function Install-IcingaAgentCertificates()
if ((Start-IcingaAgentCertificateProcess -Arguments $arguments) -eq $FALSE) {
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' `
'to your Icinga ca.crt and use the CA-Proxy certificate handling.';
'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.';
return $FALSE;
}
}
@ -178,7 +178,7 @@ function Test-IcingaAgentCertificates()
}
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;
}

View file

@ -8,9 +8,9 @@ function Compare-IcingaVersions()
if ([string]::IsNullOrEmpty($RequiredVersion)) {
return $FALSE;
}
$RequiredVersion = Split-IcingaVersion -Version $RequiredVersion;
if ([string]::IsNullOrEmpty($CurrentVersion) -eq $FALSE) {
$CurrentVersion = Split-IcingaVersion -Version $CurrentVersion;
} else {

View file

@ -19,7 +19,7 @@ function Start-IcingaAgentDirectorWizard()
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) {
$OverrideDirectorVars = $TRUE;
} else{
} else {
$OverrideDirectorVars = $FALSE;
}
}
@ -115,7 +115,7 @@ function Start-IcingaAgentDirectorWizard()
$DirectorOverrideArgs.Add(
'OverrideDirectorVars', 0
);
if ([string]::IsNullOrEmpty($TemplateKey) -eq $FALSE) {
$DirectorOverrideArgs.Add(
'SelfServiceAPIKey', $TemplateKey

View file

@ -106,7 +106,7 @@ function Start-IcingaAgentInstallWizard()
$InstallerArguments = $Result.Args;
$Result = Set-IcingaWizardArgument -DirectorArgs $DirectorArgs -WizardArg 'AcceptConnections' -Value $AcceptConnections -InstallerArguments $InstallerArguments;
$AcceptConnections = $Result.Value;
$InstallerArguments = $Result.Args;
$InstallerArguments = $Result.Args;
$Result = Set-IcingaWizardArgument -DirectorArgs $DirectorArgs -WizardArg 'ServiceUser' -Value $ServiceUser -InstallerArguments $InstallerArguments;
$ServiceUser = $Result.Value;
$InstallerArguments = $Result.Args;
@ -211,7 +211,7 @@ function Start-IcingaAgentInstallWizard()
if ([string]::IsNullOrEmpty($AgentVersion)) {
$AgentVersion = (Get-IcingaAgentInstallerAnswerInput -Prompt 'Please specify the version you want to install ("release", "snapshot" or a specific version like "2.11.3")' -Default 'v' -DefaultInput 'release').answer;
$InstallerArguments += "-AgentVersion '$AgentVersion'";
Write-IcingaConsoleNotice ([string]::Format('Installing Icinga version: "{0}"', $AgentVersion));
}
} else {
@ -393,7 +393,7 @@ function Start-IcingaAgentInstallWizard()
$GlobalZoneConfig += $GlobalZones;
$InstallerArguments += ("-GlobalZones " + ([string]::Join(',', $GlobalZones)));
} else {
$GlobalZones = @();
$GlobalZones = @();
$InstallerArguments += ("-GlobalZones @()");
}
} else {
@ -563,11 +563,15 @@ function Start-IcingaAgentInstallWizard()
Write-IcingaAgentApiConfig -Port $CAPort;
if ($EmptyCA -eq $TRUE -Or $CertsInstalled -eq $FALSE) {
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 ',
'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-IcingaConsoleWarning `
-Message '{0}{1}{2}{3}{4}' `
-Objects (
'Your Icinga Agent API feature has been disabled. Please provide either your ca.crt ',
'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;
if ($AddFirewallRule) {
@ -733,9 +737,9 @@ function Set-IcingaWizardArgument()
if ([string]::IsNullOrEmpty($Value) -eq $FALSE) {
$InstallerArguments = Add-InstallerArgument `
-InstallerArguments $InstallerArguments `
-Key $WizardArg `
-Value $Value;
-InstallerArguments $InstallerArguments `
-Key $WizardArg `
-Value $Value;
return @{
'Value' = $Value;

View file

@ -42,5 +42,5 @@ function Set-IcingaAgentServicePermission()
Remove-Item $SystemPermissions*;
Test-IcingaAgentServicePermission | Out-Null;
Test-IcingaAgentServicePermission | Out-Null;
}

View file

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

View file

@ -14,7 +14,7 @@ function Write-IcingaAgentApiConfig()
$ApiConf = [string]::Format('{0}{1}{2}{2}', $ApiConf, '}', "`r`n");
$ApiConf = $ApiConf.Substring(0, $ApiConf.Length - 4);
Set-Content -Path (Join-Path -Path (Get-IcingaAgentConfigDirectory) -ChildPath 'features-available\api.conf') -Value $ApiConf;
Write-IcingaConsoleNotice 'Api configuration has been written successfully';
}

View file

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

View file

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

View file

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

View file

@ -5,115 +5,115 @@
# which both contain the same members, allowing us to dynamicly use the objects
# without having to worry about exception.
#>
function New-IcingaPerformanceCounter()
{
param(
[string]$Counter = '',
[boolean]$SkipWait = $FALSE
);
# Simply use the counter name, like
# \Paging File(_total)\% Usage
if ([string]::IsNullOrEmpty($Counter) -eq $TRUE) {
return (New-IcingaPerformanceCounterNullObject -FullName $Counter -ErrorMessage 'Failed to initialise counter, as no counter was specified.');
}
[array]$CounterArray = $Counter.Split('\');
[string]$UseCounterCategory = '';
[string]$UseCounterName = '';
[string]$UseCounterInstance = '';
# If we add the counter as it should be
# \Paging File(_total)\% Usage
# the first array element will be an empty string we can skip
# Otherwise the name was wrong and we should not continue
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)));
}
# In case our Performance Counter is containing instances, we should split
# The content and read the instance and counter category out
if ($CounterArray[1].Contains('(')) {
[array]$TmpCounter = $CounterArray[1].Split('(');
$UseCounterCategory = $TmpCounter[0];
$UseCounterInstance = $TmpCounter[1].Replace(')', '');
} else {
# Otherwise we only require the category
$UseCounterCategory = $CounterArray[1];
}
# At last get the actual counter containing our values
$UseCounterName = $CounterArray[2];
# 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
# 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
# which contains the parent name including counters for all instances that
# have been found
if ($UseCounterInstance -eq '*') {
# In case we already loaded the counters once, return the finished array
# TODO: Re-Implement caching for counters
<#if ($Icinga2.Cache.PerformanceCounter.ContainsKey($Counter) -eq $TRUE) {
return (New-IcingaPerformanceCounterResult -FullName $Counter -PerformanceCounters $Icinga2.Cache.PerformanceCounter[$Counter]);
}#>
# 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
# later to a custom object
try {
[array]$AllCountersIntances = @();
$CounterInstances = New-Object System.Diagnostics.PerformanceCounterCategory($UseCounterCategory);
foreach ($instance in $CounterInstances.GetInstanceNames()) {
[string]$NewCounterName = $Counter.Replace('*', $instance);
$NewCounter = New-IcingaPerformanceCounterObject -FullName $NewCounterName -Category $UseCounterCategory -Counter $UseCounterName -Instance $instance -SkipWait $TRUE;
$AllCountersIntances += $NewCounter;
}
} catch {
function New-IcingaPerformanceCounter()
{
param(
[string]$Counter = '',
[boolean]$SkipWait = $FALSE
);
# Simply use the counter name, like
# \Paging File(_total)\% Usage
if ([string]::IsNullOrEmpty($Counter) -eq $TRUE) {
return (New-IcingaPerformanceCounterNullObject -FullName $Counter -ErrorMessage 'Failed to initialise counter, as no counter was specified.');
}
[array]$CounterArray = $Counter.Split('\');
[string]$UseCounterCategory = '';
[string]$UseCounterName = '';
[string]$UseCounterInstance = '';
# If we add the counter as it should be
# \Paging File(_total)\% Usage
# the first array element will be an empty string we can skip
# Otherwise the name was wrong and we should not continue
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)));
}
# In case our Performance Counter is containing instances, we should split
# The content and read the instance and counter category out
if ($CounterArray[1].Contains('(')) {
[array]$TmpCounter = $CounterArray[1].Split('(');
$UseCounterCategory = $TmpCounter[0];
$UseCounterInstance = $TmpCounter[1].Replace(')', '');
} else {
# Otherwise we only require the category
$UseCounterCategory = $CounterArray[1];
}
# At last get the actual counter containing our values
$UseCounterName = $CounterArray[2];
# 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
# 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
# which contains the parent name including counters for all instances that
# have been found
if ($UseCounterInstance -eq '*') {
# In case we already loaded the counters once, return the finished array
# TODO: Re-Implement caching for counters
<#if ($Icinga2.Cache.PerformanceCounter.ContainsKey($Counter) -eq $TRUE) {
return (New-IcingaPerformanceCounterResult -FullName $Counter -PerformanceCounters $Icinga2.Cache.PerformanceCounter[$Counter]);
}#>
# 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
# later to a custom object
try {
[array]$AllCountersIntances = @();
$CounterInstances = New-Object System.Diagnostics.PerformanceCounterCategory($UseCounterCategory);
foreach ($instance in $CounterInstances.GetInstanceNames()) {
[string]$NewCounterName = $Counter.Replace('*', $instance);
$NewCounter = New-IcingaPerformanceCounterObject -FullName $NewCounterName -Category $UseCounterCategory -Counter $UseCounterName -Instance $instance -SkipWait $TRUE;
$AllCountersIntances += $NewCounter;
}
} catch {
# 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.InvalidOperationException' -ExceptionType 'Input' -CustomMessage $Counter -ExceptionThrown $IcingaExceptions.Inputs.PerformanceCounter;
Exit-IcingaThrowException -InputString $_.Exception -StringPattern '' -ExceptionType 'Unhandled';
# 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)));
}
}
# 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
if ($SkipWait -eq $FALSE) {
# 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
if ($SkipWait -eq $FALSE) {
Start-Sleep -Milliseconds 500;
}
# Add the parent counter including the array of Performance Counters to our
# caching mechanism and return the New-IcingaPerformanceCounterResult object for usage
# within the monitoring modules
# TODO: Re-Implement caching for counters
# $Icinga2.Cache.PerformanceCounter.Add($Counter, $AllCountersIntances);
return (New-IcingaPerformanceCounterResult -FullName $Counter -PerformanceCounters $AllCountersIntances);
} else {
# This part will handle the counters without any instances as well as
# specificly assigned instances, like (_Total) CPU usage.
# In case we already have the counter within our cache, return the
# cached informations
# TODO: Re-Implement caching for counters
<#if ($Icinga2.Cache.PerformanceCounter.ContainsKey($Counter) -eq $TRUE) {
return $Icinga2.Cache.PerformanceCounter[$Counter];
}#>
# If the cache is not present yet, create the Performance Counter object,
# and add it to our cache
$NewCounter = New-IcingaPerformanceCounterObject -FullName $Counter -Category $UseCounterCategory -Counter $UseCounterName -Instance $UseCounterInstance -SkipWait $SkipWait;
# TODO: Re-Implement caching for counters
#$Icinga2.Cache.PerformanceCounter.Add($Counter, $NewCounter);
return $NewCounter; #TODO: Remove once caching is implemented
}
# This function will always return non-instance counters or
# specificly defined instance counters. Performance Counter Arrays
# are returned within their function. This is just to ensure that the
# function looks finished from developer point of view
# TODO: Re-Implement caching for counters, right now we return $NewCounter by default
#return $Icinga2.Cache.PerformanceCounter[$Counter];
}
}
# Add the parent counter including the array of Performance Counters to our
# caching mechanism and return the New-IcingaPerformanceCounterResult object for usage
# within the monitoring modules
# TODO: Re-Implement caching for counters
# $Icinga2.Cache.PerformanceCounter.Add($Counter, $AllCountersIntances);
return (New-IcingaPerformanceCounterResult -FullName $Counter -PerformanceCounters $AllCountersIntances);
} else {
# This part will handle the counters without any instances as well as
# specificly assigned instances, like (_Total) CPU usage.
# In case we already have the counter within our cache, return the
# cached informations
# TODO: Re-Implement caching for counters
<#if ($Icinga2.Cache.PerformanceCounter.ContainsKey($Counter) -eq $TRUE) {
return $Icinga2.Cache.PerformanceCounter[$Counter];
}#>
# If the cache is not present yet, create the Performance Counter object,
# and add it to our cache
$NewCounter = New-IcingaPerformanceCounterObject -FullName $Counter -Category $UseCounterCategory -Counter $UseCounterName -Instance $UseCounterInstance -SkipWait $SkipWait;
# TODO: Re-Implement caching for counters
#$Icinga2.Cache.PerformanceCounter.Add($Counter, $NewCounter);
return $NewCounter; #TODO: Remove once caching is implemented
}
# This function will always return non-instance counters or
# specificly defined instance counters. Performance Counter Arrays
# are returned within their function. This is just to ensure that the
# function looks finished from developer point of view
# TODO: Re-Implement caching for counters, right now we return $NewCounter by default
#return $Icinga2.Cache.PerformanceCounter[$Counter];
}

View file

@ -5,33 +5,32 @@
# the same member functions but allowing us to maintain
# stability without unwanted exceptions
#>
function New-IcingaPerformanceCounterNullObject()
{
param(
[string]$FullName = '',
[string]$ErrorMessage = ''
);
function New-IcingaPerformanceCounterNullObject()
{
param(
[string]$FullName = '',
[string]$ErrorMessage = ''
);
$pc_instance = New-Object -TypeName PSObject;
$pc_instance | Add-Member -membertype NoteProperty -name 'FullName' -value $FullName;
$pc_instance | Add-Member -membertype NoteProperty -name 'ErrorMessage' -value $ErrorMessage;
$pc_instance = New-Object -TypeName PSObject;
$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 ScriptMethod -name 'Name' -value {
return $this.FullName;
}
$pc_instance | Add-Member -MemberType ScriptMethod -Name 'Name' -Value {
return $this.FullName;
}
$pc_instance | Add-Member -membertype ScriptMethod -name 'Value' -value {
[hashtable]$ErrorMessage = @{};
$pc_instance | Add-Member -MemberType ScriptMethod -Name 'Value' -Value {
[hashtable]$ErrorMessage = @{};
$ErrorMessage.Add('value', $null);
$ErrorMessage.Add('sample', $null);
$ErrorMessage.Add('help', $null);
$ErrorMessage.Add('type', $null);
$ErrorMessage.Add('error', $this.ErrorMessage);
$ErrorMessage.Add('value', $null);
$ErrorMessage.Add('sample', $null);
$ErrorMessage.Add('help', $null);
$ErrorMessage.Add('type', $null);
$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,
# objects created by this function are used.
#>
function New-IcingaPerformanceCounterObject()
{
param(
[string]$FullName = '',
[string]$Category = '',
[string]$Instance = '',
[string]$Counter = '',
[boolean]$SkipWait = $FALSE
);
$pc_instance = New-Object -TypeName PSObject;
$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 'Instance' -value $Instance;
$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 'SkipWait' -value $SkipWait;
$pc_instance | Add-Member -membertype ScriptMethod -name 'Init' -value {
function New-IcingaPerformanceCounterObject()
{
param(
[string]$FullName = '',
[string]$Category = '',
[string]$Instance = '',
[string]$Counter = '',
[boolean]$SkipWait = $FALSE
);
$pc_instance = New-Object -TypeName PSObject;
$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 'Instance' -Value $Instance;
$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 'SkipWait' -Value $SkipWait;
$pc_instance | Add-Member -MemberType ScriptMethod -Name 'Init' -Value {
Write-IcingaConsoleDebug `
-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;
# Create the Performance Counter object we want to access
$this.PerfCounter = New-Object System.Diagnostics.PerformanceCounter;
$this.PerfCounter.CategoryName = $this.Category;
$this.PerfCounter.CounterName = $this.Counter;
# Only add an instance in case it is defined
if ([string]::IsNullOrEmpty($this.Instance) -eq $FALSE) {
$this.PerfCounter.InstanceName = $this.Instance
}
# Initialise the counter
try {
$this.PerfCounter.NextValue() | Out-Null;
} catch {
# Nothing to do here, will be handled later
}
<#
# 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
# 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
#>
if ($this.SkipWait -eq $FALSE) {
Start-Sleep -Milliseconds 500;
}
}
# Return the name of the counter as string
$pc_instance | Add-Member -membertype ScriptMethod -name 'Name' -value {
return $this.FullName;
}
<#
# Return a hashtable containting the counter value including the
# Sample values for the counter itself. In case we run into an error,
# keep the counter construct but add an error message in addition.
#>
$pc_instance | Add-Member -membertype ScriptMethod -name 'Value' -value {
[hashtable]$CounterData = @{};
try {
[string]$CounterType = $this.PerfCounter.CounterType;
$CounterData.Add('value', $this.PerfCounter.NextValue());
$CounterData.Add('sample', $this.PerfCounter.NextSample());
$CounterData.Add('help', $this.PerfCounter.CounterHelp);
$CounterData.Add('type', $CounterType);
$CounterData.Add('error', $null);
} catch {
$CounterData = @{};
$CounterData.Add('value', $null);
$CounterData.Add('sample', $null);
$CounterData.Add('help', $null);
$CounterData.Add('type', $null);
$CounterData.Add('error', $_.Exception.Message);
}
return $CounterData;
}
# Initialiste the entire counter and internal handlers
$pc_instance.Init();
# Return this custom object
return $pc_instance;
}
# Create the Performance Counter object we want to access
$this.PerfCounter = New-Object System.Diagnostics.PerformanceCounter;
$this.PerfCounter.CategoryName = $this.Category;
$this.PerfCounter.CounterName = $this.Counter;
# Only add an instance in case it is defined
if ([string]::IsNullOrEmpty($this.Instance) -eq $FALSE) {
$this.PerfCounter.InstanceName = $this.Instance
}
# Initialise the counter
try {
$this.PerfCounter.NextValue() | Out-Null;
} catch {
# Nothing to do here, will be handled later
}
<#
# 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
# 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
#>
if ($this.SkipWait -eq $FALSE) {
Start-Sleep -Milliseconds 500;
}
}
# Return the name of the counter as string
$pc_instance | Add-Member -MemberType ScriptMethod -Name 'Name' -Value {
return $this.FullName;
}
<#
# Return a hashtable containting the counter value including the
# Sample values for the counter itself. In case we run into an error,
# keep the counter construct but add an error message in addition.
#>
$pc_instance | Add-Member -MemberType ScriptMethod -Name 'Value' -Value {
[hashtable]$CounterData = @{};
try {
[string]$CounterType = $this.PerfCounter.CounterType;
$CounterData.Add('value', $this.PerfCounter.NextValue());
$CounterData.Add('sample', $this.PerfCounter.NextSample());
$CounterData.Add('help', $this.PerfCounter.CounterHelp);
$CounterData.Add('type', $CounterType);
$CounterData.Add('error', $null);
} catch {
$CounterData = @{};
$CounterData.Add('value', $null);
$CounterData.Add('sample', $null);
$CounterData.Add('help', $null);
$CounterData.Add('type', $null);
$CounterData.Add('error', $_.Exception.Message);
}
return $CounterData;
}
# Initialiste the entire counter and internal handlers
$pc_instance.Init();
# Return this custom object
return $pc_instance;
}

View file

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

View file

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

View file

@ -37,7 +37,7 @@ function New-IcingaThreadInstance()
Add-Member -InputObject $Thread -MemberType NoteProperty -Name Handle -Value $null;
Add-Member -InputObject $Thread -MemberType NoteProperty -Name Started -Value $FALSE;
}
if ($global:IcingaDaemonData.IcingaThreads.ContainsKey($Name) -eq $FALSE) {
$global:IcingaDaemonData.IcingaThreads.Add($Name, $Thread);
} else {

View file

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

View file

@ -1,7 +1,7 @@
function ConvertFrom-IcingaSecureString()
{
param([SecureString]$SecureString);
if ($SecureString -eq $null) {
return '';
}

View file

@ -1,21 +1,21 @@
function ConvertTo-ByteIEC()
{
param(
[single]$Value,
[string]$Unit
[single]$Value,
[string]$Unit
);
switch ($Unit) {
{ 'B', 'Byte' -contains $_ } { $result = $Value; $boolOption = $true; }
{ 'KiB', 'Kibibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 10)); $boolOption = $true; }
{ 'MiB', 'Mebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 20)); $boolOption = $true; }
{ 'MiB', 'Mebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 20)); $boolOption = $true; }
{ 'GiB', 'Gibibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 30)); $boolOption = $true; }
{ 'TiB', 'Tebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 40)); $boolOption = $true; }
{ 'PiB', 'Pebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 50)); $boolOption = $true; }
default {
default {
if (-Not $boolOption) {
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;
}
}
}
}
@ -32,17 +32,17 @@ function ConvertTo-Kibibyte()
switch ($Unit) {
{ 'B', 'Byte' -contains $_ } { $result = ($Value / [math]::Pow(2, 10)); $boolOption = $true; }
{ 'KiB', 'Kibibyte' -contains $_ } { $result = $Value; $boolOption = $true; }
{ 'MiB', 'Mebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 10)); $boolOption = $true; }
{ 'MiB', 'Mebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 10)); $boolOption = $true; }
{ 'GiB', 'Gibibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 20)); $boolOption = $true; }
{ 'TiB', 'Tebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 30)); $boolOption = $true; }
{ 'PiB', 'Pebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 40)); $boolOption = $true; }
default {
default {
if (-Not $boolOption) {
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;
}
}
}
}
return $result;
}
@ -56,17 +56,17 @@ function ConvertTo-Mebibyte()
switch ($Unit) {
{ 'B', 'Byte' -contains $_ } { $result = ($Value / [math]::Pow(2, 20)); $boolOption = $true; }
{ 'KiB', 'Kibibyte' -contains $_ } { $result = ($Value / [math]::Pow(2, 10)); $boolOption = $true; }
{ 'MiB', 'Mebibyte' -contains $_ } { $result = $Value; $boolOption = $true; }
{ 'MiB', 'Mebibyte' -contains $_ } { $result = $Value; $boolOption = $true; }
{ 'GiB', 'Gibibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 10)); $boolOption = $true; }
{ 'TiB', 'Tebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 20)); $boolOption = $true; }
{ 'PiB', 'Pebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 30)); $boolOption = $true; }
default {
default {
if (-Not $boolOption) {
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;
}
}
}
}
return $result;
}
@ -84,13 +84,13 @@ function ConvertTo-Gibibyte()
{ 'GiB', 'Gibibyte' -contains $_ } { $result = $Value; $boolOption = $true; }
{ 'TiB', 'Tebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 10)); $boolOption = $true; }
{ 'PiB', 'Pebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 20)); $boolOption = $true; }
default {
default {
if (-Not $boolOption) {
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;
}
}
}
}
return $result;
}
@ -108,13 +108,13 @@ function ConvertTo-Tebibyte()
{ 'GiB', 'Gibibyte' -contains $_ } { $result = ($Value / [math]::Pow(2, 10)); $boolOption = $true; }
{ 'TiB', 'Tebibyte' -contains $_ } { $result = $Value; $boolOption = $true; }
{ 'PiB', 'Pebibyte' -contains $_ } { $result = ($Value * [math]::Pow(2, 10)); $boolOption = $true; }
default {
default {
if (-Not $boolOption) {
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;
}
}
}
}
return $result;
}
@ -132,12 +132,12 @@ function ConvertTo-Pebibyte()
{ 'GiB', 'Gibibyte' -contains $_ } { $result = ($Value / [math]::Pow(2, 20)); $boolOption = $true; }
{ 'TiB', 'Tebibyte' -contains $_ } { $result = ($Value / [math]::Pow(2, 10)); $boolOption = $true; }
{ 'PiB', 'Pebibyte' -contains $_ } { $result = $Value; $boolOption = $true; }
default {
default {
if (-Not $boolOption) {
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;
}
}
}
}
return $result;
}

View file

@ -17,21 +17,21 @@
function ConvertTo-ByteSI()
{
param(
[single]$Value,
[string]$Unit
[single]$Value,
[string]$Unit
);
switch ($Unit) {
{ 'B', 'Byte' -contains $_ } { $result = $Value; $boolOption = $true; }
{ 'KB', 'Kilobyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 3)); $boolOption = $true; }
{ 'MB', 'Megabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 6)); $boolOption = $true; }
{ 'MB', 'Megabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 6)); $boolOption = $true; }
{ 'GB', 'Gigabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 9)); $boolOption = $true; }
{ 'TB', 'Terabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 12)); $boolOption = $true; }
{ 'PB', 'Petabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 15)); $boolOption = $true; }
default {
default {
if (-Not $boolOption) {
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;
}
}
}
}
@ -64,17 +64,17 @@ function ConvertTo-Kilobyte()
switch ($Unit) {
{ 'B', 'Byte' -contains $_ } { $result = ($Value / [math]::Pow(10, 3)); $boolOption = $true; }
{ 'KB', 'Kilobyte' -contains $_ } { $result = $Value; $boolOption = $true; }
{ 'MB', 'Megabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 3)); $boolOption = $true; }
{ 'MB', 'Megabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 3)); $boolOption = $true; }
{ 'GB', 'Gigabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 6)); $boolOption = $true; }
{ 'TB', 'Terabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 9)); $boolOption = $true; }
{ 'PB', 'Petabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 12)); $boolOption = $true; }
default {
default {
if (-Not $boolOption) {
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;
}
}
}
}
return $result;
}
@ -104,17 +104,17 @@ function ConvertTo-Megabyte()
switch ($Unit) {
{ 'B', 'Byte' -contains $_ } { $result = ($Value / [math]::Pow(10, 6)); $boolOption = $true; }
{ 'KB', 'Kilobyte' -contains $_ } { $result = ($Value / [math]::Pow(10, 3)); $boolOption = $true; }
{ 'MB', 'Megabyte' -contains $_ } { $result = $Value; $boolOption = $true; }
{ 'MB', 'Megabyte' -contains $_ } { $result = $Value; $boolOption = $true; }
{ 'GB', 'Gigabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 3)); $boolOption = $true; }
{ 'TB', 'Terabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 6)); $boolOption = $true; }
{ 'PB', 'Petabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 9)); $boolOption = $true; }
default {
default {
if (-Not $boolOption) {
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;
}
}
}
}
return $result;
}
@ -148,13 +148,13 @@ function ConvertTo-Gigabyte()
{ 'GB', 'Gigabyte' -contains $_ } { $result = $Value; $boolOption = $true; }
{ 'TB', 'Terabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 3)); $boolOption = $true; }
{ 'PB', 'Petabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 6)); $boolOption = $true; }
default {
default {
if (-Not $boolOption) {
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;
}
}
}
}
return $result;
}
@ -188,13 +188,13 @@ function ConvertTo-Terabyte()
{ 'GB', 'Gigabyte' -contains $_ } { $result = ($Value / [math]::Pow(10, 3)); $boolOption = $true; }
{ 'TB', 'Terabyte' -contains $_ } { $result = $Value; $boolOption = $true; }
{ 'PB', 'Petabyte' -contains $_ } { $result = ($Value * [math]::Pow(10, 3)); $boolOption = $true; }
default {
default {
if (-Not $boolOption) {
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;
}
}
}
}
return $result;
}
@ -228,12 +228,12 @@ function ConvertTo-Petabyte()
{ 'GB', 'Gigabyte' -contains $_ } { $result = ($Value / [math]::Pow(10, 6)); $boolOption = $true; }
{ 'TB', 'Terabyte' -contains $_ } { $result = ($Value / [math]::Pow(10, 3)); $boolOption = $true; }
{ 'PB', 'Petabyte' -contains $_ } { $result = $Value; $boolOption = $true; }
default {
default {
if (-Not $boolOption) {
Exit-IcingaThrowException -ExceptionType 'Input' -ExceptionThrown $IcingaExceptions.Inputs.ConversionUnitMissing -Force;
}
}
}
}
return $result;
}

View file

@ -1,37 +1,37 @@
<#
.SYNOPSIS
Used to convert both IPv4 addresses and IPv6 addresses to binary.
Used to convert both IPv4 addresses and IPv6 addresses to binary.
.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
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
Used to specify an IPv4 address or IPv6 address.
Used to specify an IPv4 address or IPv6 address.
.INPUTS
System.String
System.String
.OUTPUTS
System.String
System.String
.LINK
https://github.com/Icinga/icinga-powershell-framework
https://github.com/Icinga/icinga-powershell-framework
.NOTES
#>
function ConvertTo-IcingaIPBinaryString()
{
param(
$IP
);
param (
$IP
);
if ($IP -like '*.*') {
$IP = ConvertTo-IcingaIPv4BinaryString -IP $IP;
} elseif ($IP -like '*:*') {
$IP = ConvertTo-IcingaIPv6BinaryString -IP $IP;
} else {
return 'Invalid IP was provided!';
}
if ($IP -like '*.*') {
$IP = ConvertTo-IcingaIPv4BinaryString -IP $IP;
} elseif ($IP -like '*:*') {
$IP = ConvertTo-IcingaIPv6BinaryString -IP $IP;
} else {
return 'Invalid IP was provided!';
}
return $IP;
return $IP;
}

View file

@ -21,24 +21,24 @@
function ConvertTo-IcingaIPv4BinaryString()
{
param(
[string]$IP
);
param(
[string]$IP
);
try {
$IP = $IP -split '\.' | ForEach-Object {
[System.Convert]::ToString($_, 2).PadLeft(8, '0');
}
$IP = $IP -join '';
$IP = $IP -replace '\s','';
} catch {
# 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
return $null;
}
try {
$IP = $IP -split '\.' | ForEach-Object {
[System.Convert]::ToString($_, 2).PadLeft(8, '0');
}
$IP = $IP -join '';
$IP = $IP -replace '\s', '';
} catch {
# 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
return $null;
}
return @{
'value' = $IP;
'name' = 'IPv4'
}
return @{
'value' = $IP;
'name' = 'IPv4'
}
}

View file

@ -29,13 +29,13 @@ function ConvertTo-IcingaIPv6BinaryString()
$IPArr = $IPArr.ToCharArray();
$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 -replace '\s','';
$IP = $IP -replace '\s', '';
return @{
'value' = $IP;
'name' = 'IPv6'
}
'value' = $IP;
'name' = 'IPv6'
}
}

View file

@ -60,6 +60,6 @@ function ConvertTo-Integer()
return 0;
}
}
return $Value;
}

View file

@ -37,7 +37,7 @@ function ConvertTo-Seconds()
[bool]$Negate = $FALSE;
[bool]$hasUnit = $FALSE;
foreach($char in $Value.ToCharArray()) {
foreach ($char in $Value.ToCharArray()) {
if ((Test-Numeric $char)) {
$NumberPart += $char;
} else {
@ -82,7 +82,7 @@ function ConvertTo-Seconds()
{ 119 -contains $_ } { $result = $ValueSplitted * 604800; break; } # w
{ 77 -contains $_ } { $result = $ValueSplitted * 2592000; break; } # M
{ 121 -contains $_ } { $result = $ValueSplitted * 31536000; break; } # y
default {
default {
Throw $errorMsg;
break;
}

View file

@ -8,7 +8,7 @@
.FUNCTIONALITY
This module is intended to be used to expand an IPv6 address.
.EXAMPLE
PS> Expand-IcingaIPv6String ffe8::71:ab:
PS> Expand-IcingaIPv6String ffe8::71:ab:
FFE8:0000:0000:0000:0000:0071:00AB:0000
.PARAMETER IP
Used to specify an IPv6 address.
@ -34,7 +34,7 @@ function Expand-IcingaIPv6String()
for ($Index = 0; $Index -lt $IP.Length; $Index++) {
if ($IP[$Index] -eq ':') {
$Counter++;
if (($Index - 1) -ge 0 -and $IP[$Index - 1] -eq ':'){
if (($Index - 1) -ge 0 -and $IP[$Index - 1] -eq ':') {
$RelV = $Index;
}
}

View file

@ -64,7 +64,6 @@
function Get-IcingaCheckCommandConfig()
{
param(
[Parameter(ValueFromPipeline)]
[array]$CheckName,
[string]$OutDirectory
);
@ -74,7 +73,7 @@ function Get-IcingaCheckCommandConfig()
$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 = @{};
# Define basic hashtable structure by adding fields: "Datafield", "DataList", "Command"
@ -103,7 +102,7 @@ function Get-IcingaCheckCommandConfig()
# Loop through ${CheckName}, to get information on every command specified/all commands.
foreach ($check in $CheckName) {
# Get necessary syntax-information and more through cmdlet "Get-Help"
$Data = (Get-Help $check);
$ParameterList = (Get-Command -Name $check).Parameters;
@ -159,8 +158,8 @@ function Get-IcingaCheckCommandConfig()
$Basket.Command[$Data.Name].vars.Add($parameter.Name, $FALSE);
# Conditional whether type of parameter is array
} elseif ($parameter.type.name -eq 'Array') {
# Conditional whether type of parameter is array
$Basket.Command[$Data.Name].arguments.Add(
[string]::Format('-{0}', $parameter.Name), @{
'value' = @{
@ -316,7 +315,7 @@ function Get-IcingaCheckCommandConfig()
if ((Test-Path($OutDirectory)) -eq $false) {
throw 'Failed to create specified directory. Please try again or use a different target location.';
}
Set-Content -Path $OutDirectory -Value $output;
# Output-Text

View file

@ -11,7 +11,7 @@
PS> Get-IcingaNetworkInterface 'icinga.com'
192.168.243.88
.EXAMPLE
PS> Get-IcingaNetworkInterface '8.8.8.8'
PS> Get-IcingaNetworkInterface '8.8.8.8'
192.168.243.88
.PARAMETER IP
Used to specify either an IPv4, IPv6 address or an FQDN.
@ -59,26 +59,19 @@ function Get-IcingaNetworkInterface()
foreach ($destinationIP in $IPBinStringMaster) {
[string]$Key = '';
[string]$MaskKey = '';
############################################################################
################################ IPv4 ####################################
############################################################################
<# IPv4 #>
if ($destinationIP.name -eq 'IPv4') {
if ($IP -like '*.*') {
############################################################################
if ([int]$Mask -lt 10) {
$MaskKey = [string]::Format('00{0}', $Mask);
} else {
$MaskKey = [string]::Format('0{0}', $Mask);
}
############################################################################
}
}
############################################################################
################################ IPv6 ####################################
############################################################################
<# IPv6 #>
if ($destinationIP.name -eq 'IPv6') {
if ($IP -like '*:*') {
############################################################################
if ([int]$Mask -lt 10) {
$MaskKey = [string]::Format('00{0}', $Mask);
} elseif ([int]$Mask -lt 100) {
@ -86,7 +79,6 @@ function Get-IcingaNetworkInterface()
} else {
$MaskKey = $Mask;
}
############################################################################
}
}
@ -144,7 +136,7 @@ function Get-IcingaNetworkInterface()
if ($ExternalInterfaces.Count -eq 0) {
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)) {
$ExternalInterfaces[$ExternalInterface].count += 1;
} else {
@ -155,7 +147,7 @@ function Get-IcingaNetworkInterface()
}
);
}
}
}
}
$InternalCount = 0;

View file

@ -40,7 +40,7 @@ function Get-IcingaPSObjectProperties()
([string]$property.Value)
);
}
}
}

View file

@ -21,7 +21,7 @@ function Get-IcingaServices()
[hashtable]$ServiceData = @{};
foreach ($service in $ServiceInformation) {
[array]$DependentServices = $null;
[array]$DependingServices = $null;
$ServiceExitCode = 0;
@ -46,7 +46,7 @@ function Get-IcingaServices()
}
$DependentServices += $dependency.Name;
}
#Depends / Parent
foreach ($dependency in $service.ServicesDependedOn) {
if ($null -eq $DependingServices) {

View file

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

View file

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

View file

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

View file

@ -19,6 +19,6 @@ function Join-WebPath()
if ($ChildPath[0] -eq '/') {
return ([string]::Format('{0}{1}', $Path, $ChildPath));
}
return ([string]::Format('{0}/{1}', $Path, $ChildPath));
}

View file

@ -3,13 +3,13 @@ function New-StringTree()
param(
[int]$Spacing
)
if ($Spacing -eq 0) {
return '';
}
[string]$spaces = '\_ ';
while ($Spacing -gt 1) {
$Spacing -= 1;
$spaces = ' ' + $spaces;

View file

@ -14,6 +14,6 @@ function Pop-IcingaArrayListItem()
$Content = $Array[0];
$Array.RemoveAt(0);
return $Content;
}

View file

@ -11,7 +11,7 @@ function Start-IcingaPowerShellDaemon()
try {
$EnabledDaemons = Get-IcingaBackgroundDaemons;
foreach ($daemon in $EnabledDaemons.Keys) {
if (-Not (Test-IcingaFunction $daemon)) {
continue;

View file

@ -2,7 +2,7 @@ Import-IcingaLib icinga\plugin;
function Get-IcingaHelpThresholds()
{
param(
param (
$Value,
$Warning,
$Critical
@ -46,7 +46,7 @@ function Get-IcingaHelpThresholds()
Get-IcingaHelpThresholds -Value 5 -Warning "30:50" -Critical "10:70"; #This will return Critical
#####################
Outside Range
-Warning "@40:70"
@ -58,7 +58,7 @@ function Get-IcingaHelpThresholds()
Get-IcingaHelpThresholds -Value 50 -Warning "@20:90" -Critical "@40:60"; #This will return Critical
#####################
Above value
-Warning "50:"
@ -70,7 +70,7 @@ function Get-IcingaHelpThresholds()
Get-IcingaHelpThresholds -Value 10 -Warning "90:" -Critical "50:"; #This will return Critical
#####################
Below value
-Warning "~:40"

View file

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

View file

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

View file

@ -16,27 +16,27 @@ function New-IcingaCheckPackage()
);
$Check = New-Object -TypeName PSObject;
$Check | Add-Member -membertype NoteProperty -name 'name' -value $Name;
$Check | Add-Member -membertype NoteProperty -name 'exitcode' -value -1;
$Check | Add-Member -membertype NoteProperty -name 'verbose' -value $Verbose;
$Check | Add-Member -membertype NoteProperty -name 'hidden' -value $Hidden;
$Check | Add-Member -membertype NoteProperty -name 'checks' -value $Checks;
$Check | Add-Member -membertype NoteProperty -name 'opand' -value $OperatorAnd;
$Check | Add-Member -membertype NoteProperty -name 'opor' -value $OperatorOr;
$Check | Add-Member -membertype NoteProperty -name 'opnone' -value $OperatorNone;
$Check | Add-Member -membertype NoteProperty -name 'opmin' -value $OperatorMin;
$Check | Add-Member -membertype NoteProperty -name 'opmax' -value $OperatorMax;
$Check | Add-Member -membertype NoteProperty -name 'spacing' -value 0;
$Check | Add-Member -membertype NoteProperty -name 'compiled' -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 'headermsg' -value '';
$Check | Add-Member -membertype NoteProperty -name 'checkpackage' -value $TRUE;
$Check | Add-Member -membertype NoteProperty -name 'warningchecks' -value @();
$Check | Add-Member -membertype NoteProperty -name 'criticalchecks' -value @();
$Check | Add-Member -membertype NoteProperty -name 'unknownchecks' -value @();
$Check | Add-Member -MemberType NoteProperty -Name 'name' -Value $Name;
$Check | Add-Member -MemberType NoteProperty -Name 'exitcode' -Value -1;
$Check | Add-Member -MemberType NoteProperty -Name 'verbose' -Value $Verbose;
$Check | Add-Member -MemberType NoteProperty -Name 'hidden' -Value $Hidden;
$Check | Add-Member -MemberType NoteProperty -Name 'checks' -Value $Checks;
$Check | Add-Member -MemberType NoteProperty -Name 'opand' -Value $OperatorAnd;
$Check | Add-Member -MemberType NoteProperty -Name 'opor' -Value $OperatorOr;
$Check | Add-Member -MemberType NoteProperty -Name 'opnone' -Value $OperatorNone;
$Check | Add-Member -MemberType NoteProperty -Name 'opmin' -Value $OperatorMin;
$Check | Add-Member -MemberType NoteProperty -Name 'opmax' -Value $OperatorMax;
$Check | Add-Member -MemberType NoteProperty -Name 'spacing' -Value 0;
$Check | Add-Member -MemberType NoteProperty -Name 'compiled' -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 'headermsg' -Value '';
$Check | Add-Member -MemberType NoteProperty -Name 'checkpackage' -Value $TRUE;
$Check | Add-Member -MemberType NoteProperty -Name 'warningchecks' -Value @();
$Check | Add-Member -MemberType NoteProperty -Name 'criticalchecks' -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) {
return $TRUE
}
@ -44,13 +44,13 @@ function New-IcingaCheckPackage()
return $FALSE;
}
$Check | Add-Member -membertype ScriptMethod -name 'Initialise' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'Initialise' -Value {
foreach ($check in $this.checks) {
$this.InitCheck($check);
}
}
$Check | Add-Member -membertype ScriptMethod -name 'InitCheck' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'InitCheck' -Value {
param($check);
if ($null -eq $check) {
@ -62,7 +62,7 @@ function New-IcingaCheckPackage()
$check.SilentCompile();
}
$Check | Add-Member -membertype ScriptMethod -name 'AddSpacing' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'AddSpacing' -Value {
$this.spacing += 1;
foreach ($check in $this.checks) {
$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);
if ($null -eq $check) {
@ -81,7 +81,7 @@ function New-IcingaCheckPackage()
$this.checks += $check;
}
$Check | Add-Member -membertype ScriptMethod -name 'GetWarnings' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'GetWarnings' -Value {
foreach ($check in $this.checks) {
$this.warningchecks += $check.GetWarnings();
}
@ -89,7 +89,7 @@ function New-IcingaCheckPackage()
return $this.warningchecks;
}
$Check | Add-Member -membertype ScriptMethod -name 'GetCriticals' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'GetCriticals' -Value {
foreach ($check in $this.checks) {
$this.criticalchecks += $check.GetCriticals();
}
@ -97,7 +97,7 @@ function New-IcingaCheckPackage()
return $this.criticalchecks;
}
$Check | Add-Member -membertype ScriptMethod -name 'GetUnknowns' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'GetUnknowns' -Value {
foreach ($check in $this.checks) {
$this.unknownchecks += $check.GetUnknowns();
}
@ -105,7 +105,7 @@ function New-IcingaCheckPackage()
return $this.unknownchecks;
}
$Check | Add-Member -membertype ScriptMethod -name 'AssignCheckCommand' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'AssignCheckCommand' -Value {
param($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);
if ($this.compiled) {
@ -129,24 +129,24 @@ function New-IcingaCheckPackage()
if ($this.CheckAllOk() -eq $FALSE) {
$this.GetWorstExitCode();
}
} elseif($this.opor) {
} elseif ($this.opor) {
if ($this.CheckOneOk() -eq $FALSE) {
$this.GetWorstExitCode();
}
} elseif($this.opnone) {
} elseif ($this.opnone) {
if ($this.CheckOneOk() -eq $TRUE) {
$this.GetWorstExitCode();
$this.exitcode = $IcingaEnums.IcingaExitCode.Critical;
} else {
$this.exitcode = $IcingaEnums.IcingaExitCode.Ok;
}
} elseif([int]$this.opmin -ne -1) {
} elseif ([int]$this.opmin -ne -1) {
if ($this.CheckMinimumOk() -eq $FALSE) {
$this.GetWorstExitCode();
} else {
$this.exitcode = $IcingaEnums.IcingaExitCode.Ok;
}
} elseif([int]$this.opmax -ne -1) {
} elseif ([int]$this.opmax -ne -1) {
if ($this.CheckMaximumOk() -eq $FALSE) {
$this.GetWorstExitCode();
} else {
@ -168,11 +168,11 @@ function New-IcingaCheckPackage()
return $this.exitcode;
}
$Check | Add-Member -membertype ScriptMethod -name 'SilentCompile' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'SilentCompile' -Value {
$this.Compile($FALSE) | Out-Null;
}
$Check | Add-Member -membertype ScriptMethod -name 'GetOkCount' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'GetOkCount' -Value {
[int]$okCount = 0;
foreach ($check in $this.checks) {
if ([int]$check.exitcode -eq [int]$IcingaEnums.IcingaExitCode.Ok) {
@ -183,12 +183,14 @@ function New-IcingaCheckPackage()
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) {
Write-IcingaPluginOutput ([string]::Format(
'Unknown: The minimum argument ({0}) is exceeding the amount of assigned checks ({1}) to this package "{2}"',
$this.opmin, $this.checks.Count, $this.name
));
Write-IcingaPluginOutput (
[string]::Format(
'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;
return $FALSE;
}
@ -202,12 +204,14 @@ function New-IcingaCheckPackage()
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) {
Write-IcingaPluginOutput ([string]::Format(
'Unknown: The maximum argument ({0}) is exceeding the amount of assigned checks ({1}) to this package "{2}"',
$this.opmax, $this.checks.Count, $this.name
));
Write-IcingaPluginOutput (
[string]::Format(
'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;
return $FALSE;
}
@ -221,7 +225,7 @@ function New-IcingaCheckPackage()
return $FALSE;
}
$Check | Add-Member -membertype ScriptMethod -name 'CheckAllOk' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'CheckAllOk' -Value {
foreach ($check in $this.checks) {
if ([int]$check.exitcode -ne [int]$IcingaEnums.IcingaExitCode.Ok) {
return $FALSE;
@ -231,7 +235,7 @@ function New-IcingaCheckPackage()
return $TRUE;
}
$Check | Add-Member -membertype ScriptMethod -name 'CheckOneOk' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'CheckOneOk' -Value {
foreach ($check in $this.checks) {
if ([int]$check.exitcode -eq [int]$IcingaEnums.IcingaExitCode.Ok) {
$this.exitcode = $check.exitcode;
@ -242,7 +246,7 @@ function New-IcingaCheckPackage()
return $FALSE;
}
$Check | Add-Member -membertype ScriptMethod -name 'GetPackageConfigMessage' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'GetPackageConfigMessage' -Value {
if ($this.opand) {
return 'Match All';
} 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);
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);
}
$Check | Add-Member -membertype ScriptMethod -name 'PrintAllMessages' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'PrintAllMessages' -Value {
$this.WritePackageOutputStatus();
$this.WriteAllOutput();
}
$Check | Add-Member -membertype ScriptMethod -name 'WriteCheckErrors' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'WriteCheckErrors' -Value {
$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) {
Write-IcingaPluginOutput (
[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) {
return;
}
@ -344,15 +348,15 @@ function New-IcingaCheckPackage()
);
}
$Check | Add-Member -membertype ScriptMethod -name 'PrintOutputMessages' -value {
$Check | Add-Member -MemberType ScriptMethod -Name 'PrintOutputMessages' -Value {
[bool]$printAll = $FALSE;
switch ($this.verbose) {
0 {
0 {
# Default value. Only print a package but not the services include
break;
break;
};
1 {
1 {
# Include the Operator into the check package result
break;
};
@ -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);
[hashtable]$CheckHash = @{};
@ -393,11 +397,11 @@ function New-IcingaCheckPackage()
'{0} {1} ',
$IcingaEnums.IcingaExitCodeText[$state],
[string]::Join(', ', $SortedCheckArray.Key)
);
);
}
}
$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) {
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 = '';
[hashtable]$CollectedPerfData = @{};

View file

@ -9,10 +9,10 @@ function New-IcingaCheckresult()
);
$CheckResult = New-Object -TypeName PSObject;
$CheckResult | Add-Member -membertype NoteProperty -name 'check' -value $Check;
$CheckResult | Add-Member -membertype NoteProperty -name 'noperfdata' -value $NoPerfData;
$CheckResult | Add-Member -MemberType NoteProperty -Name 'check' -Value $Check;
$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) {
return $IcingaEnums.IcingaExitCode.Unknown;
}

View file

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

View file

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

View file

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

View file

@ -11,7 +11,7 @@ function Get-IcingaRESTPathElement()
if ($Request.ContainsKey('RequestPath') -eq $FALSE) {
return '';
}
}
if (($Index + 1) -gt $Request.RequestPath.PathArray.Count) {
return '';

View file

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

View file

@ -21,7 +21,7 @@ function Read-IcingaRESTMessage()
[hashtable]$Request = @{};
$RestMessage -match '(.+) (.+) (.+)' | Out-Null;
$Request.Add('Method', $Matches[1]);
$Request.Add('FullRequest', $Matches[2]);
$Request.Add('RequestPath', @{});
@ -39,7 +39,7 @@ function Read-IcingaRESTMessage()
# Arguments
$ArgumentsSplit = $Arguments.Split('&');
$ArgumentsSplit+='\\\\\\\\\\\\=FIN';
foreach ( $Argument in $ArgumentsSplit | Sort-Object -descending) {
foreach ( $Argument in $ArgumentsSplit | Sort-Object -Descending) {
if ($Argument.Contains('=')) {
$Argument -match '(.+)=(.+)' | Out-Null;
If (($Matches[1] -ne $Current) -And ($NULL -ne $Current)) {
@ -58,7 +58,7 @@ function Read-IcingaRESTMessage()
$SplitString = $RestMessage.split("`r`n");
foreach ( $SingleString in $SplitString ) {
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());
}
}

View file

@ -1,3 +1,4 @@
<#
.SYNOPSIS
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]$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) {
$AuthMethod = [System.DirectoryServices.AccountManagement.ContextType]::Domain;
$AuthDomain = $Domain;
@ -63,9 +64,10 @@ function Test-IcingaRESTCredentials()
try {
# Try to authenticate and either return true or false as integer
[bool]$AuthResult = [int]($AccountService.ValidateCredentials(
(ConvertFrom-IcingaSecureString $UserName),
(ConvertFrom-IcingaSecureString $Password)
));
(ConvertFrom-IcingaSecureString $UserName),
(ConvertFrom-IcingaSecureString $Password)
)
);
return $AuthResult;
} catch {