Merge pull request #366 from Icinga:fix/icinga_director_error_handling_imc

Fix: Improves error handling on IMC for Director

Fixes error message handling for Icinga Director while using IMC.
This commit is contained in:
Lord Hepipud 2021-09-10 11:41:22 +02:00 committed by GitHub
commit d02a12ead1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 168 additions and 31 deletions

View file

@ -17,6 +17,7 @@ Released closed milestones can be found on [GitHub](https://github.com/Icinga/ic
* [#362](https://github.com/Icinga/icinga-powershell-framework/issues/362) Fixes repository component installation from file share locations * [#362](https://github.com/Icinga/icinga-powershell-framework/issues/362) Fixes repository component installation from file share locations
* [#363](https://github.com/Icinga/icinga-powershell-framework/issues/363) Fixes unneeded continue for JEA process lookup, in case no JEA pid is present * [#363](https://github.com/Icinga/icinga-powershell-framework/issues/363) Fixes unneeded continue for JEA process lookup, in case no JEA pid is present
* [#365](https://github.com/Icinga/icinga-powershell-framework/issues/365) Fixes Icinga environment corruption on Icinga Agent installation failure * [#365](https://github.com/Icinga/icinga-powershell-framework/issues/365) Fixes Icinga environment corruption on Icinga Agent installation failure
* [#366](https://github.com/Icinga/icinga-powershell-framework/issues/366) Fixes error handling with Icinga Director over IMC, by printing more detailed and user-friendly error messages
### Enhancements ### Enhancements

View file

@ -42,10 +42,31 @@ function Get-IcingaDirectorSelfServiceConfig()
$EndpointUrl = Join-WebPath -Path $DirectorUrl -ChildPath ([string]::Format('/self-service/powershell-parameters?key={0}', $ApiKey)); $EndpointUrl = Join-WebPath -Path $DirectorUrl -ChildPath ([string]::Format('/self-service/powershell-parameters?key={0}', $ApiKey));
$response = Invoke-IcingaWebRequest -Uri $EndpointUrl -UseBasicParsing -Headers @{ 'accept' = 'application/json'; 'X-Director-Accept' = 'application/json' } -Method 'POST'; $response = Invoke-IcingaWebRequest -Uri $EndpointUrl -UseBasicParsing -Headers @{ 'accept' = 'application/json'; 'X-Director-Accept' = 'application/json' } -Method 'POST' -NoErrorMessage;
if ($response.StatusCode -ne 200) { if ($response.StatusCode -ne 200) {
throw $response.Content; $ErrorMessage = '';
switch ($response.StatusCode) {
403 {
$ErrorMessage = 'Failed to fetch configuration for host over Self-Service API with key "{0}". This error mostly occurs in case the host object itself is not defined as "Icinga2 Agent" object inside the Icinga Director.';
break;
};
404 {
$ErrorMessage = 'Failed to fetch configuration for host over Self-Service API with key "{0}". Probably the assigned host/template key is not valid or your Icinga Director Url is invalid "{1}".';
break;
};
901 {
$ErrorMessage = 'Failed to fetch host/template configuration from Icinga Director Self-Service API because of SSL/TLS error. Please ensure the certificate is valid and use "Enable-IcingaUntrustedCertificateValidation" for self-signed certificates or install the certificate on this machine.';
break;
}
Default {
$ErrorMessage = ([string]::Format('Failed to fetch host/template configuration from Icinga Director Self-Service API because of unhandled exception: {0}', $response.StatusCode));
break;
};
}
Write-IcingaConsoleError $ErrorMessage -Objects $ApiKey, $DirectorUrl;
throw $ErrorMessage;
} }
$JsonContent = ConvertFrom-Json -InputObject $response.Content; $JsonContent = ConvertFrom-Json -InputObject $response.Content;

View file

@ -42,10 +42,31 @@ function Get-IcingaDirectorSelfServiceTicket()
[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-IcingaWebRequest -Uri $url -UseBasicParsing -Headers @{ 'accept' = 'application/json'; 'X-Director-Accept' = 'application/json' } -Method 'POST'; $response = Invoke-IcingaWebRequest -Uri $url -UseBasicParsing -Headers @{ 'accept' = 'application/json'; 'X-Director-Accept' = 'application/json' } -Method 'POST' -NoErrorMessage;
if ($response.StatusCode -ne 200) { if ($response.StatusCode -ne 200) {
throw $response.Content; $ErrorMessage = '';
switch ($response.StatusCode) {
404 {
$ErrorMessage = 'Failed to fetch certificate ticket for this host over Self-Service API. Please check that your Icinga Director Url "{1}" is valid and the provided API key "{0}" belongs to a Icinga host object.';
break;
};
500 {
$ErrorMessage = 'Failed to fetch certificate ticket for this host over Self-Service API. Please check that your Icinga CA is running, you have configured a Ticketsalt and that your Icinga Director has enough permissions to communicate with the Icinga 2 API for generating tickets.';
break;
};
901 {
$ErrorMessage = 'Failed to fetch certificate ticket for this host over Self-Service API because of SSL/TLS error. Please ensure the certificate is valid and use "Enable-IcingaUntrustedCertificateValidation" for self-signed certificates or install the certificate on this machine.';
break;
}
Default {
$ErrorMessage = ([string]::Format('Failed to fetch certificate ticket from Icinga Director because of unhandled exception: {0}', $response.StatusCode));
break;
};
}
Write-IcingaConsoleError $ErrorMessage -Objects $ApiKey, $DirectorUrl;
throw $ErrorMessage;
} }
$JsonContent = ConvertFrom-Json -InputObject $response.Content; $JsonContent = ConvertFrom-Json -InputObject $response.Content;

View file

@ -66,10 +66,31 @@ function Register-IcingaDirectorSelfServiceHost()
$EndpointUrl = Join-WebPath -Path $DirectorUrl -ChildPath ([string]::Format('/self-service/register-host?name={0}&key={1}', $Hostname, $ApiKey)); $EndpointUrl = Join-WebPath -Path $DirectorUrl -ChildPath ([string]::Format('/self-service/register-host?name={0}&key={1}', $Hostname, $ApiKey));
$response = Invoke-IcingaWebRequest -Uri $EndpointUrl -UseBasicParsing -Headers @{ 'accept' = 'application/json'; 'X-Director-Accept' = 'application/json' } -Method 'POST' -Body $DirectorConfigJson; $response = Invoke-IcingaWebRequest -Uri $EndpointUrl -UseBasicParsing -Headers @{ 'accept' = 'application/json'; 'X-Director-Accept' = 'application/json' } -Method 'POST' -Body $DirectorConfigJson -NoErrorMessage;
if ($response.StatusCode -ne 200) { if ($response.StatusCode -ne 200) {
throw $response.Content; $ErrorMessage = '';
switch ($response.StatusCode) {
400 {
Write-IcingaConsoleWarning 'Failed to register host inside Icinga Director. The host is probably already registered.'
return $null;
};
404 {
$ErrorMessage = 'Failed to register host with the given API key "{0}" inside Icinga Director. Please ensure the template key you are using is correct and the template is set as "Icinga2 Agent" object. Non-Agent templates will not work over the Self-Service API.';
break;
};
901 {
$ErrorMessage = 'Failed to register host over Self-Service API inside Icinga Director because of SSL/TLS error. Please ensure the certificate is valid and use "Enable-IcingaUntrustedCertificateValidation" for self-signed certificates or install the certificate on this machine.';
break;
}
Default {
$ErrorMessage = ([string]::Format('Failed to register host inside Icinga Director because of unhandled exception: {0}', $response.StatusCode));
break;
};
}
Write-IcingaConsoleError $ErrorMessage -Objects $ApiKey;
throw $ErrorMessage;
} }
$JsonContent = ConvertFrom-Json -InputObject $response.Content; $JsonContent = ConvertFrom-Json -InputObject $response.Content;

View file

@ -91,10 +91,20 @@ function Start-IcingaAgentDirectorWizard()
if ($HostKnown -eq $FALSE) { if ($HostKnown -eq $FALSE) {
while ($TRUE) { while ($TRUE) {
[bool]$RegisterFailed = $FALSE;
try { try {
$SelfServiceAPIKey = Register-IcingaDirectorSelfServiceHost -DirectorUrl $DirectorUrl -ApiKey $SelfServiceAPIKey -Hostname (Get-IcingaHostname @Arguments) -Endpoint $Arguments.IcingaMaster; $SelfServiceAPIKey = Register-IcingaDirectorSelfServiceHost -DirectorUrl $DirectorUrl -ApiKey $SelfServiceAPIKey -Hostname (Get-IcingaHostname @Arguments) -Endpoint $Arguments.IcingaMaster;
if ([string]::IsNullOrEmpty($SelfServiceAPIKey) -eq $FALSE) {
break; break;
} else {
$RegisterFailed = $TRUE;
}
} catch { } catch {
$RegisterFailed = $TRUE;
}
if ($RegisterFailed) {
$SelfServiceAPIKey = (Get-IcingaAgentInstallerAnswerInput -Prompt ([string]::Format('Failed to register host within Icinga Director. Full error: "{0}". Please re-enter your SelfService API Key. If this prompt continues ensure you are using an Agent template or drop your host key at "Hosts -> {1} -> Agent"', $_.Exception.Message, (Get-IcingaHostname @Arguments))) -Default 'v' -DefaultInput $SelfServiceAPIKey).answer; $SelfServiceAPIKey = (Get-IcingaAgentInstallerAnswerInput -Prompt ([string]::Format('Failed to register host within Icinga Director. Full error: "{0}". Please re-enter your SelfService API Key. If this prompt continues ensure you are using an Agent template or drop your host key at "Hosts -> {1} -> Agent"', $_.Exception.Message, (Get-IcingaHostname @Arguments))) -Default 'v' -DefaultInput $SelfServiceAPIKey).answer;
} }
} }

View file

@ -16,9 +16,11 @@ function Install-Icinga()
'LastInput' = ''; 'LastInput' = '';
'LastNotice' = ''; 'LastNotice' = '';
'LastError' = ''; 'LastError' = '';
'DirectorError' = '';
'HeaderPreview' = ''; 'HeaderPreview' = '';
'DirectorSelfService' = $FALSE; 'DirectorSelfService' = $FALSE;
'DirectorRegisteredHost' = $FALSE; 'DirectorRegisteredHost' = $FALSE;
'DirectorInstallError' = $FALSE;
'LastParent' = [System.Collections.ArrayList]@(); 'LastParent' = [System.Collections.ArrayList]@();
'LastValues' = @(); 'LastValues' = @();
'DisabledEntries' = @{ }; 'DisabledEntries' = @{ };
@ -61,6 +63,7 @@ function Install-Icinga()
# In case we use the director, we require to first fetch all basic values from the Self-Service API then # In case we use the director, we require to first fetch all basic values from the Self-Service API then
# require to register the host to fet the remaining content # require to register the host to fet the remaining content
if ($IcingaConfiguration.ContainsKey('IfW-DirectorSelfServiceKey') -And $IcingaConfiguration.ContainsKey('IfW-DirectorUrl')) { if ($IcingaConfiguration.ContainsKey('IfW-DirectorSelfServiceKey') -And $IcingaConfiguration.ContainsKey('IfW-DirectorUrl')) {
Enable-IcingaFrameworkConsoleOutput;
Resolve-IcingaForWindowsManagementConsoleInstallationDirectorTemplate; Resolve-IcingaForWindowsManagementConsoleInstallationDirectorTemplate;
Resolve-IcingaForWindowsManagementConsoleInstallationDirectorTemplate -Register; Resolve-IcingaForWindowsManagementConsoleInstallationDirectorTemplate -Register;
Disable-IcingaFrameworkConsoleOutput; Disable-IcingaFrameworkConsoleOutput;

View file

@ -4,12 +4,18 @@ function Start-IcingaForWindowsInstallation()
[switch]$Automated [switch]$Automated
); );
if ((Get-IcingaFrameworkDebugMode) -eq $FALSE) { if ($global:Icinga.InstallWizard.DirectorInstallError -eq $FALSE -And (Get-IcingaFrameworkDebugMode) -eq $FALSE) {
Clear-Host; Clear-Host;
} }
Write-IcingaConsoleNotice 'Starting Icinga for Windows installation'; Write-IcingaConsoleNotice 'Starting Icinga for Windows installation';
if ($global:Icinga.InstallWizard.DirectorInstallError) {
Write-IcingaConsoleError 'Failed to start Icinga for Windows installation, caused by an error while communicating with Icinga Director: {0}' -Objects $global:Icinga.InstallWizard.DirectorError;
throw $global:Icinga.InstallWizard.DirectorError;
return;
}
$ConnectionType = Get-IcingaForWindowsInstallerStepSelection -InstallerStep 'Show-IcingaForWindowsInstallerMenuSelectConnection'; $ConnectionType = Get-IcingaForWindowsInstallerStepSelection -InstallerStep 'Show-IcingaForWindowsInstallerMenuSelectConnection';
$HostnameType = Get-IcingaForWindowsInstallerStepSelection -InstallerStep 'Show-IcingaForWindowsInstallerMenuSelectHostname'; $HostnameType = Get-IcingaForWindowsInstallerStepSelection -InstallerStep 'Show-IcingaForWindowsInstallerMenuSelectHostname';
$FirewallType = Get-IcingaForWindowsInstallerStepSelection -InstallerStep 'Show-IcingaForWindowsInstallerMenuSelectOpenWindowsFirewall'; $FirewallType = Get-IcingaForWindowsInstallerStepSelection -InstallerStep 'Show-IcingaForWindowsInstallerMenuSelectOpenWindowsFirewall';

View file

@ -46,10 +46,20 @@ function Resolve-IcingaForWindowsManagementConsoleInstallationDirectorTemplate()
}; };
} }
[bool]$RegisterFailed = $FALSE;
try { try {
$SelfServiceKey = Register-IcingaDirectorSelfServiceHost -DirectorUrl $DirectorUrl -ApiKey $SelfServiceKey -Hostname $Hostname; $SelfServiceKey = Register-IcingaDirectorSelfServiceHost -DirectorUrl $DirectorUrl -ApiKey $SelfServiceKey -Hostname $Hostname;
if ([string]::IsNullOrEmpty($SelfServiceKey) -eq $FALSE) {
$UsedEnteredKey = $SelfServiceKey; $UsedEnteredKey = $SelfServiceKey;
} else {
$RegisterFailed = $TRUE;
}
} catch { } catch {
$RegisterFailed = $TRUE;
}
if ($RegisterFailed) {
Write-IcingaConsoleNotice 'Host seems already to be registered within Icinga Director. Trying local Api key if present' Write-IcingaConsoleNotice 'Host seems already to be registered within Icinga Director. Trying local Api key if present'
$SelfServiceKey = Get-IcingaPowerShellConfig -Path 'IcingaDirector.SelfService.ApiKey'; $SelfServiceKey = Get-IcingaPowerShellConfig -Path 'IcingaDirector.SelfService.ApiKey';
@ -57,6 +67,7 @@ function Resolve-IcingaForWindowsManagementConsoleInstallationDirectorTemplate()
Write-IcingaConsoleNotice 'No local Api key was found and using your provided template key failed. Please ensure the host is not already registered and drop the set Self-Service key within the Icinga Director for this host.' Write-IcingaConsoleNotice 'No local Api key was found and using your provided template key failed. Please ensure the host is not already registered and drop the set Self-Service key within the Icinga Director for this host.'
} }
} }
Add-IcingaForWindowsInstallerConfigEntry -Selection 'c' -Values $UsedEnteredKey -OverwriteValues -OverwriteMenu 'Show-IcingaForWindowsManagementConsoleInstallationEnterDirectorSelfServiceKey'; Add-IcingaForWindowsInstallerConfigEntry -Selection 'c' -Values $UsedEnteredKey -OverwriteValues -OverwriteMenu 'Show-IcingaForWindowsManagementConsoleInstallationEnterDirectorSelfServiceKey';
} }
@ -65,9 +76,14 @@ function Resolve-IcingaForWindowsManagementConsoleInstallationDirectorTemplate()
} catch { } catch {
Set-IcingaForWindowsManagementConsoleMenu 'Show-IcingaForWindowsInstallerConfigurationSummary'; Set-IcingaForWindowsManagementConsoleMenu 'Show-IcingaForWindowsInstallerConfigurationSummary';
$global:Icinga.InstallWizard.LastError = 'Failed to fetch host configuration with the given Director Url and Self-Service key. Please ensure the template key is correct and in case a previous host key was used, that it matches the one configured within the Icinga Director. In case this form was loaded previously with a key, it might be that the host key is no longer valid and requires to be dropped. In addition please ensure that this host can connect to the Icinga Director and the SSL certificate is trusted. Otherwise run "Enable-IcingaUntrustedCertificateValidation" before starting the management console. Otherwise modify the "DirectorSelfServiceKey" configuration element above with the correct key and try again.'; $global:Icinga.InstallWizard.LastError = 'Failed to fetch host configuration with the given Director Url and Self-Service key. Please ensure the template key is correct and in case a previous host key was used, that it matches the one configured within the Icinga Director. In case this form was loaded previously with a key, it might be that the host key is no longer valid and requires to be dropped. In addition please ensure that this host can connect to the Icinga Director and the SSL certificate is trusted. Otherwise run "Enable-IcingaUntrustedCertificateValidation" before starting the management console. Otherwise modify the "DirectorSelfServiceKey" configuration element above with the correct key and try again.';
$global:Icinga.InstallWizard.DirectorError = $global:Icinga.InstallWizard.LastError;
$global:Icinga.InstallWizard.DirectorInstallError = $TRUE;
return; return;
} }
$global:Icinga.InstallWizard.DirectorInstallError = $FALSE;
$global:Icinga.InstallWizard.DirectorError = '';
# No we need to identify which host selection is matching our config # No we need to identify which host selection is matching our config
$HostnameSelection = 1; $HostnameSelection = 1;
$InstallPluginsSelection = 0; $InstallPluginsSelection = 0;

View file

@ -22,7 +22,7 @@ function Show-IcingaForWindowsInstallerMenu()
[switch]$NoConfigSwap = $FALSE [switch]$NoConfigSwap = $FALSE
); );
if ((Test-IcingaForWindowsInstallationHeaderPrint) -eq $FALSE -And (Get-IcingaFrameworkDebugMode) -eq $FALSE) { if ($global:Icinga.InstallWizard.DirectorInstallError -eq $FALSE -And (Test-IcingaForWindowsInstallationHeaderPrint) -eq $FALSE -And (Get-IcingaFrameworkDebugMode) -eq $FALSE) {
Clear-Host; Clear-Host;
} }

View file

@ -23,7 +23,8 @@ function Write-IcingaConsoleDebug()
{ {
param ( param (
[string]$Message, [string]$Message,
[array]$Objects [array]$Objects,
[switch]$DropMessage = $FALSE
); );
if ((Get-IcingaFrameworkDebugMode) -eq $FALSE) { if ((Get-IcingaFrameworkDebugMode) -eq $FALSE) {
@ -34,5 +35,6 @@ function Write-IcingaConsoleDebug()
-Message $Message ` -Message $Message `
-Objects $Objects ` -Objects $Objects `
-ForeColor 'Blue' ` -ForeColor 'Blue' `
-Severity 'Debug'; -Severity 'Debug' `
-DropMessage:$DropMessage;
} }

View file

@ -23,12 +23,14 @@ function Write-IcingaConsoleError()
{ {
param ( param (
[string]$Message, [string]$Message,
[array]$Objects [array]$Objects,
[switch]$DropMessage = $FALSE
); );
Write-IcingaConsoleOutput ` Write-IcingaConsoleOutput `
-Message $Message ` -Message $Message `
-Objects $Objects ` -Objects $Objects `
-ForeColor 'Red' ` -ForeColor 'Red' `
-Severity 'Error'; -Severity 'Error' `
-DropMessage:$DropMessage;
} }

View file

@ -23,12 +23,14 @@ function Write-IcingaConsoleNotice()
{ {
param ( param (
[string]$Message, [string]$Message,
[array]$Objects [array]$Objects,
[switch]$DropMessage = $FALSE
); );
Write-IcingaConsoleOutput ` Write-IcingaConsoleOutput `
-Message $Message ` -Message $Message `
-Objects $Objects ` -Objects $Objects `
-ForeColor 'Green' ` -ForeColor 'Green' `
-Severity 'Notice'; -Severity 'Notice' `
-DropMessage:$DropMessage;
} }

View file

@ -20,6 +20,11 @@
The color the severity name will be displayed in The color the severity name will be displayed in
.PARAMETER Severity .PARAMETER Severity
The severity being displayed before the actual message. Leave empty to skip. The severity being displayed before the actual message. Leave empty to skip.
.PARAMETER NoNewLine
Will ensure that no new line is added at the end of the message, allowing to
write different messages with different function calls without line breaks
.PARAMETER DropMessage
Will not write the message to the console and simply drop it
.INPUTS .INPUTS
System.String System.String
.LINK .LINK
@ -34,9 +39,14 @@ function Write-IcingaConsoleOutput()
[ValidateSet('Default', 'Black', 'DarkBlue', 'DarkGreen', 'DarkCyan', 'DarkRed', 'DarkMagenta', 'DarkYellow', 'Gray', 'DarkGray', 'Blue', 'Green', 'Cyan', 'Red', 'Magenta', 'Yellow', 'White')] [ValidateSet('Default', 'Black', 'DarkBlue', 'DarkGreen', 'DarkCyan', 'DarkRed', 'DarkMagenta', 'DarkYellow', 'Gray', 'DarkGray', 'Blue', 'Green', 'Cyan', 'Red', 'Magenta', 'Yellow', 'White')]
[string]$ForeColor = 'Default', [string]$ForeColor = 'Default',
[string]$Severity = 'Notice', [string]$Severity = 'Notice',
[switch]$NoNewLine = $FALSE [switch]$NoNewLine = $FALSE,
[switch]$DropMessage = $FALSE
); );
if ($DropMessage) {
return;
}
if ((Test-IcingaFrameworkConsoleOutput) -eq $FALSE) { if ((Test-IcingaFrameworkConsoleOutput) -eq $FALSE) {
return; return;
} }

View file

@ -26,7 +26,8 @@ function Write-IcingaConsolePlain()
[array]$Objects, [array]$Objects,
[ValidateSet('Default', 'Black', 'DarkBlue', 'DarkGreen', 'DarkCyan', 'DarkRed', 'DarkMagenta', 'DarkYellow', 'Gray', 'DarkGray', 'Blue', 'Green', 'Cyan', 'Red', 'Magenta', 'Yellow', 'White')] [ValidateSet('Default', 'Black', 'DarkBlue', 'DarkGreen', 'DarkCyan', 'DarkRed', 'DarkMagenta', 'DarkYellow', 'Gray', 'DarkGray', 'Blue', 'Green', 'Cyan', 'Red', 'Magenta', 'Yellow', 'White')]
[string]$ForeColor = 'Default', [string]$ForeColor = 'Default',
[switch]$NoNewLine = $FALSE [switch]$NoNewLine = $FALSE,
[switch]$DropMessage = $FALSE
); );
Write-IcingaConsoleOutput ` Write-IcingaConsoleOutput `
@ -34,5 +35,6 @@ function Write-IcingaConsolePlain()
-Objects $Objects ` -Objects $Objects `
-ForeColor $ForeColor ` -ForeColor $ForeColor `
-Severity $null ` -Severity $null `
-NoNewLine:$NoNewLine; -NoNewLine:$NoNewLine `
-DropMessage:$DropMessage;
} }

View file

@ -23,12 +23,14 @@ function Write-IcingaConsoleWarning()
{ {
param ( param (
[string]$Message, [string]$Message,
[array]$Objects [array]$Objects,
[switch]$DropMessage = $FALSE
); );
Write-IcingaConsoleOutput ` Write-IcingaConsoleOutput `
-Message $Message ` -Message $Message `
-Objects $Objects ` -Objects $Objects `
-ForeColor 'DarkYellow' ` -ForeColor 'DarkYellow' `
-Severity 'Warning'; -Severity 'Warning' `
-DropMessage:$DropMessage;
} }

View file

@ -46,6 +46,8 @@
.PARAMETER Objects .PARAMETER Objects
Use placeholders within the `-Uri` argument, like {0} and replace them with array elements of this argument. Use placeholders within the `-Uri` argument, like {0} and replace them with array elements of this argument.
The index entry of {0} has to match the order of this argument. The index entry of {0} has to match the order of this argument.
.PARAMETER NoErrorMessage
Will not print any error message caused by invalid requests or errors
.INPUTS .INPUTS
System.String System.String
.OUTPUTS .OUTPUTS
@ -64,7 +66,8 @@ function Invoke-IcingaWebRequest()
[string]$Method = 'Get', [string]$Method = 'Get',
[string]$OutFile, [string]$OutFile,
[switch]$UseBasicParsing, [switch]$UseBasicParsing,
[array]$Objects = @() [array]$Objects = @(),
[switch]$NoErrorMessage = $FALSE
); );
[int]$Index = 0; [int]$Index = 0;
@ -109,27 +112,42 @@ function Invoke-IcingaWebRequest()
Set-IcingaTLSVersion; Set-IcingaTLSVersion;
Disable-IcingaProgressPreference; Disable-IcingaProgressPreference;
$ErrorStatus = 900;
try { try {
$Response = Invoke-WebRequest -UseBasicParsing:$UseBasicParsing @WebArguments -ErrorAction Stop; $Response = Invoke-WebRequest -UseBasicParsing:$UseBasicParsing @WebArguments;
} catch { } catch {
[string]$ErrorId = ([string]$_.FullyQualifiedErrorId).Split(',')[0]; [string]$ErrorId = ([string]$_.FullyQualifiedErrorId).Split(',')[0];
[string]$Message = $_.Exception.Message; [string]$Message = $_.Exception.Message;
if ([string]::IsNullOrEmpty($_.Exception.Response.StatusCode.Value__) -eq $FALSE) {
$ErrorStatus = $_.Exception.Response.StatusCode.Value__;
}
if ($_.Exception.ToString().Contains('TlsStream')) {
$ErrorId = 'System.Net.TlsStream.Exception';
}
switch ($ErrorId) { switch ($ErrorId) {
'System.UriFormatException' { 'System.UriFormatException' {
Write-IcingaConsoleError 'The provided Url "{0}" is not a valid format' -Objects $Uri; Write-IcingaConsoleError 'The provided Url "{0}" is not a valid format. Response: "{1}"' -Objects $Uri, $Message -DropMessage:$NoErrorMessage;
break; break;
}; };
'WebCmdletWebResponseException' { 'WebCmdletWebResponseException' {
Write-IcingaConsoleError 'The remote host for address "{0}" could not be resolved' -Objects $Uri; Write-IcingaConsoleError 'The remote host "{0}" send an exception response "{1}": "{2}"' -Objects $Uri, $ErrorStatus, $Message -DropMessage:$NoErrorMessage;
break; break;
}; };
'System.InvalidOperationException' { 'System.InvalidOperationException' {
Write-IcingaConsoleError 'Failed to query host "{0}". Possible this is caused by an invalid Proxy Server configuration: "{1}".' -Objects $Uri, $ProxyServer; Write-IcingaConsoleError 'Failed to query host "{0}". Possible this is caused by an invalid Proxy Server configuration: "{1}". Response: "{2}"' -Objects $Uri, $ProxyServer, $Message -DropMessage:$NoErrorMessage;
break; break;
}; };
'System.Net.TlsStream.Exception' {
Write-IcingaConsoleError 'Failed to establish secure SSL/TLS connection to "{0}". Please ensure the certificate is valid and trusted and use "Set-IcingaTLSVersion" on older Windows machines. If you are using self-signed certificates, install them locally or use "Enable-IcingaUntrustedCertitifacateValidation". Error Message: "{1}"' -Objects $Uri, $Message -DropMessage:$NoErrorMessage;
$ErrorStatus = 901;
break;
}
Default { Default {
Write-IcingaConsoleError 'Unhandled exception for Url "{0}" with error id "{1}":{2}{2}{3}' -Objects $Uri, $ErrorId, (New-IcingaNewLine), $Message; Write-IcingaConsoleError 'Unhandled exception for Url "{0}" with error id "{1}":{2}{2}{3}{2}Response: "{4}"' -Objects $Uri, $ErrorId, (New-IcingaNewLine), $Message -DropMessage:$NoErrorMessage;
break; break;
}; };
} }
@ -142,7 +160,7 @@ function Invoke-IcingaWebRequest()
'AbsoluteUri' = $Uri; 'AbsoluteUri' = $Uri;
}; };
}; };
'StatusCode' = 900; 'StatusCode' = $ErrorStatus;
}; };
} }