Public/test-connection.ps1

function Test-CSConnection {
    <#
    .SYNOPSIS
        Tests the CloudStack connection by making a simple API call.

    .DESCRIPTION
        Attempts to list zones to verify the connection is working properly.
        This is useful for troubleshooting connection and authentication issues.

    .OUTPUTS
        System.Boolean. $true if the API call succeeded, otherwise $false.

    .EXAMPLE
        Test-CSConnection -Verbose
    #>

    [CmdletBinding()]
    [OutputType([bool])]
    param()

    try {
        Write-Host "Testing CloudStack connection..." -ForegroundColor Cyan

        $connection = Get-CSConnection
        Write-Verbose "Base URL: $($connection.BaseUrl)"
        Write-Verbose "API Key: $($connection.ApiKey.Substring(0, [Math]::Min(8, $connection.ApiKey.Length)))..."

        # Try a simple API call (listZones)
        Write-Host "Making test API call (listZones)..."
        $response = Invoke-CSApiRequest -Command 'listZones' -Parameters @{}

        if ($response.listzonesresponse.zone) {
            $zoneCount = ($response.listzonesresponse.zone | Measure-Object).Count
            Write-Host "✓ Connection successful!" -ForegroundColor Green
            Write-Host " Found $zoneCount zone(s)" -ForegroundColor Green
            return $true
        }
        else {
            Write-Host "✓ Connection successful (no zones returned)" -ForegroundColor Green
            return $true
        }
    }
    catch {
        Write-Host "✗ Connection failed!" -ForegroundColor Red
        Write-Host " Error: $_" -ForegroundColor Red
        return $false
    }
}

function Debug-CSConnection {
    <#
    .SYNOPSIS
        Walks through connecting to a CloudStack server and reports where it fails.

    .DESCRIPTION
        A guided troubleshooting wrapper around Connect-CSServer and
        Test-CSConnection. Connects with the supplied credentials, makes a test
        API call, and prints targeted next steps when a step fails.

        Use Test-CSConnection directly if you only need a pass/fail check
        against an already-established connection.

    .PARAMETER Server
        CloudStack server URL, including the port (e.g. https://cloud.example.com:443).

    .PARAMETER ApiKey
        CloudStack API key.

    .PARAMETER SecretKey
        CloudStack secret key.

    .PARAMETER ApiPath
        Optional API path override. Try '/api' if the default '/client/api' fails.

    .OUTPUTS
        System.Boolean. $true if the test API call succeeded, otherwise $false.

    .EXAMPLE
        Debug-CSConnection -Server 'https://cloud.example.com:443' -ApiKey $key -SecretKey $secret

    .EXAMPLE
        # Retry against the alternate API path
        Debug-CSConnection -Server $url -ApiKey $key -SecretKey $secret -ApiPath '/api'
    #>

    [CmdletBinding()]
    [OutputType([bool])]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$Server,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$ApiKey,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$SecretKey,

        [Parameter(Mandatory = $false)]
        [string]$ApiPath
    )

    Write-Host "`n========================================" -ForegroundColor Cyan
    Write-Host "CloudStack Connection Test" -ForegroundColor Cyan
    Write-Host "========================================`n" -ForegroundColor Cyan

    # Step 1: Connect to Server
    Write-Host "[Step 1] Connecting to CloudStack server..." -ForegroundColor Yellow
    Write-Host " Server: $Server" -ForegroundColor Gray

    try {
        if ($ApiPath) {
            Connect-CSServer -Server $Server -ApiKey $ApiKey -SecretKey $SecretKey -ApiPath $ApiPath
        }
        else {
            Connect-CSServer -Server $Server -ApiKey $ApiKey -SecretKey $SecretKey
        }
        Write-Host "✓ Connection parameters set`n" -ForegroundColor Green
    }
    catch {
        Write-Host "✗ Failed to set connection: $_" -ForegroundColor Red
        return $false
    }

    # Step 2: Test Connection
    Write-Host "[Step 2] Testing connection with API call..." -ForegroundColor Yellow
    Write-Host " (This will timeout after 30 seconds if unreachable)`n" -ForegroundColor Gray

    $testResult = Test-CSConnection

    if ($testResult) {
        Write-Host "`n✓ CloudStack connection is working!" -ForegroundColor Green
        Write-Host "`nYou can now try:" -ForegroundColor Cyan
        Write-Host " Get-CSVM" -ForegroundColor White
        Write-Host " Get-CSVM -Name 'tv-prv-04'" -ForegroundColor White
        Write-Host " Get-CSVM -State Running" -ForegroundColor White
    }
    else {
        Write-Host "`n✗ Connection test failed!" -ForegroundColor Red
        Write-Host "`nTroubleshooting steps:" -ForegroundColor Yellow
        Write-Host "1. Verify the server URL is correct (including port)" -ForegroundColor White
        Write-Host "2. Check if you can reach the server:" -ForegroundColor White
        Write-Host " Test-NetConnection $(($Server -replace 'https?://', '') -replace ':\d+', '') -Port $([uri]$Server).Port" -ForegroundColor Gray
        Write-Host "3. Verify your API credentials are correct" -ForegroundColor White
        Write-Host "4. Try using -ApiPath '/api' instead of default '/client/api'" -ForegroundColor White
        Write-Host "5. Check CloudStack management server logs" -ForegroundColor White
    }

    Write-Host "`n========================================`n" -ForegroundColor Cyan

    return $testResult
}
Set-Alias -Name test-csconnection -Value Debug-CSConnection