Partilhar via


Use a ferramenta de verificação de diagnóstico para diagnosticar e corrigir problemas de ambiente em caso de falha na criação de clusters AKS (Prévia)

Pode ser difícil identificar problemas relacionados ao ambiente, como a configuração de rede, que podem resultar em uma falha de criação de cluster AKS. O verificador de diagnóstico é uma ferramenta do PowerShell que pode ajudá-lo a identificar falhas de criação de cluster AKS devido a possíveis problemas no ambiente.

Nota

Você só pode usar a ferramenta de verificação de diagnóstico se um cluster AKS foi criado, mas está em um estado de falha. Você não pode usar a ferramenta se não vir um cluster AKS no portal do Azure. Se a criação do cluster AKS falhar antes de um recurso do Azure Resource Manager ser criado, arquive uma solicitação de suporte.

Antes de começar

Antes de começar, certifique-se de que tem os seguintes pré-requisitos. Se você não atender aos requisitos para executar a ferramenta de verificação de diagnóstico, envie uma solicitação de suporte:

  • Acesso direto ao cluster Local do Azure onde você criou o cluster AKS. Esse acesso pode ser por meio da área de trabalho remota (RDP) ou você também pode entrar em um dos nós físicos locais do Azure.
  • Analise os conceitos de rede para criar um cluster AKS e a arquitetura de cluster AKS.
  • O nome da rede lógica conectada ao cluster AKS.
  • Uma chave privada SSH para o cluster AKS, usada para entrar na VM do nó do plano de controle do cluster AKS.

Obter o IP da VM do nó do plano de controle do cluster AKS

Execute o seguinte comando a partir de qualquer nó físico no cluster Local do Azure. Certifique-se de que está a passar o nome, e não o ID do Azure Resource Manager do cluster AKS:

invoke-command -computername (get-clusternode) -script {get-vmnetworkadapter -vmname *} | Where-Object {$_.Name -like "$cluster_name*control-plane-*"} | select vmname, ipaddresses

Resultado esperado:

VMName                                                 IPAddresses
------                                                 -----------
<cluster-name>-XXXXXX-control-plane-XXXXXX {172.16.0.10, 172.16.0.4, fe80::ec:d3ff:fea0:1}

Se você não vir uma VM de plano de controle como mostrado na saída anterior, registre uma solicitação de suporte.

Se você vir uma VM de plano de controle e ela tiver:

  • 0 endereços IPv4: arquive uma solicitação de suporte.
  • 1 Endereço IP: use o endereço IPv4 como entrada para vmIP o parâmetro.
  • 2 endereços IP: use qualquer um dos endereços IPv4 como uma entrada para vmIP o parâmetro no verificador de diagnóstico.

Executar o script do verificador de diagnóstico

Copie o seguinte script PowerShell nomeado run_diagnostic.ps1 em qualquer nó do cluster Local do Azure.

<#
.SYNOPSIS
    Runs diagnostic checker tool in target cluster control plane VM and returns the result.

    This script runs the following tests from target cluster control plane VM:
    1. cloud-agent-connectivity-test: Checks whether the DNS server can resolve the Moc cloud agent FQDN and that the cloud agent is reachable from the control plane node VM. Cloud agent is created using one of the IP addresses from the [management IP pool](hci/plan/cloud-deployment-network-considerations.md#management-ip-pool), on port 55000. The control plane node VM is given an IP address from the Arc VM logical network.
    2. gateway-icmp-ping-test: Checks whether the gateway specified in the logical network attached to the AKS cluster is reachable from the AKS cluster control plane node VM.
    3. http-connectivity-required-url-test: Checks whether the required URLs are reachable from the AKS cluster control plane node VM.

.DESCRIPTION
    This script transfers a file from the local machine to a remote server using the SCP (Secure Copy Protocol) command.

.PARAMETER lnetName
    The name of the LNET used for the cluster.

.PARAMETER sshPath
    The path to the private SSH key for the target cluster.

.PARAMETER vmIP
    IP of the target cluster control plane VM.


.EXAMPLE
    .\run_diagnostic.ps1 -lnetName lnet1 -sshPath C:\Users\test\.ssh\test-ssh.pem -vmIP "172.16.0.10"
    This example runs diagnostic checker tool in the VM with IP 172.16.0.10 using ssh key C:\Users\test\.ssh\test-ssh.pem and outputs the result.
#>

param (
    [Parameter(Mandatory=$true)]
    [string]$lnetName,

    [Parameter(Mandatory=$true)]
    [string]$sshPath,

    [Parameter(Mandatory=$true)]
    [string]$vmIP
)

$urlArray = @(
    "https://management.azure.com",
    "https://eastus.dp.kubernetesconfiguration.azure.com",
    "https://login.microsoftonline.com",
    "https://eastus.login.microsoft.com",
    "https://login.windows.net",
    "https://mcr.microsoft.com",
    "https://gbl.his.arc.azure.com",
    "https://k8connecthelm.download.prss.microsoft.com",
    "https://guestnotificationservice.azure.com",
    "https://sts.windows.net",
    "https://graph.microsoft.com"
)
$urlList=$urlArray -join ","

# check vm is reachable
try {
  $pingResult = Test-Connection -ComputerName $vmIP -Count 1 -ErrorAction Stop
  if ($pingResult.StatusCode -eq 0) {
    Write-Host "Connection to $vmIP succeeded."
  } else {
    Write-Host "Connection to AKS cluster control plane VM $vmIP failed with status code: $($pingResult.StatusCode). Please make sure AKS cluster control plane VM $vmIP is reachable from the host"
    exit
  }
} catch {
  Write-Host "Connection to AKS cluster control plane VM $vmIP failed. Please make sure AKS cluster control plane VM $vmIP is reachable from the host"
  Write-Host "Exception message: $_"
  exit
}

# retreiving LNET 
$lnet=get-mocvirtualnetwork -group Default_Group -name $lnetName
# getting gateway address from LNET
$gateway=$lnet.properties.subnets[0].properties.routeTable.properties.routes[0].properties.nextHopIpAddress
if (-not $gateway) {
  Write-Error "Check Gateway address in the AKS logical network $lnetName"
  exit
}

# getting cloudfqdn from archciconfig
$arcHCIConfig=get-archciconfig
$cloudFqdn="http://"+$arcHCIConfig.Item('cloudFQDN')+":55000" 

$configContent = @"
checks:
- metadata:
    creationTimestamp: null
    name: cloud-agent-connectivity-test
  parameters:
    hostnames: <CLOUD_FQDN>
    skipeof: "true"
  type: HTTPConnectivity
- metadata:
    annotations:
      skip-error-on-failure: "true"
    creationTimestamp: null
    name: gateway-icmp-ping-test
  parameters:
    ips: <GATEWAY>
    packetLossThreshold: "20"
  type: ICMPPing
- metadata:
    creationTimestamp: null
    name: http-connectivity-required-url-test
  parameters:
    hostnames: <URL_LIST>
  type: HTTPConnectivity
exports:
- metadata:
    creationTimestamp: null
  parameters:
    filelocation: /home/clouduser/results.yaml
  type: FileSystem
metadata:
  creationTimestamp: null
"@

# update config file with the values of cloud fqdn, gateway and dns servers
$configContent = $configContent.replace("<CLOUD_FQDN>", $cloudFqdn)
$configContent = $configContent.replace("<GATEWAY>", $gateway)
$configContent = $configContent.replace("<URL_LIST>", $urlList)

$filePath = "config.yaml"
# Write to config.yaml
Set-Content -Path $filePath -Value $configContent

$dest = 'clouduser@' + $vmIP + ":config.yaml"

# Copy the config file to target cluster VM
Write-Host "Copying test config file to target cluster VM...."
$command = "scp -i $sshPath -o StrictHostKeyChecking=no -o BatchMode=yes config.yaml $dest"
try {
  $output=invoke-expression $command
  if ($LASTEXITCODE -ne 0) {
    Write-Error "Couldn't ssh to AKS cluster control plane VM $vmIP. Please check the ssh key"
    exit
  }
} catch {
  Write-Host "Couldn't ssh to AKS cluster control plane VM $vmIP. Please check the ssh key"
  Write-Host "Exception message: $_"
  exit
}
Write-Output "Copied config.yaml successfully."
$runScriptContent = @"
sudo su - root -c "/usr/bin/diagnostics-checker -c /home/clouduser/config.yaml"
"@

$filePath = "run_diag.sh"

Set-Content -Path $filePath -Value $runScriptContent
$dest = 'clouduser@' + $vmIP + ":run_diag.sh"
scp -i $sshPath -o StrictHostKeyChecking=no -o BatchMode=yes run_diag.sh $dest

$dest = 'clouduser@' + $vmIP
ssh -i $sshPath $dest -o StrictHostKeyChecking=no -o BatchMode=yes 'chmod +x run_diag.sh'

$sedCommand="sed -i -e 's/\r$//' run_diag.sh"
ssh -i $sshPath -o StrictHostKeyChecking=no -o BatchMode=yes $dest $sedCommand

if (Test-Path -Path "results.yaml") {
  Remove-Item results.yaml
}

ssh -i $sshPath -o StrictHostKeyChecking=no -o BatchMode=yes $dest './run_diag.sh'
ssh -i $sshPath -o StrictHostKeyChecking=no -o BatchMode=yes $dest "sudo su - root -c 'chmod a+r /home/clouduser/results.yaml'"

$src= 'clouduser@' + $vmIP + ":results.yaml"
scp -i $sshPath -o StrictHostKeyChecking=no -o BatchMode=yes $src results.yaml

if (-Not (Test-Path -Path "results.yaml")) {
  write-host "Test failed to perform"
  exit
}

Install-Module powershell-yaml

$resultContent = Get-Content -path results.yaml | ConvertFrom-Yaml

$testResults = @()
$cloudAgentRecommendation = @"
Make sure that the logical network IP addresses can connect to all the management IP pool addresses on the required ports. Check AKS network port and cross vlan requirements for detailed list of ports that need to be opened.
"@
$gatewayRecommendation = @"
- Ensure gateway is operational
- Verify routing configurations
- Adjust firewall rules to allow ICMP traffic
"@
$urlRecommendation = @"
Ensure that the logical network IP addresses have outbound internet access. If there's a firewall, ensure that AKS required URLs are accessible from Arc VM logical network.
"@


foreach ($check in $resultContent.spec.checks) {
  if ($check.result.outcome -like "Success") {
    $recommendation=""
  }elseif ($check.metadata.name -like "cloud-agent-connectivity-test") {
    $recommendation=$cloudAgentRecommendation
  }elseif ($check.metadata.name -like "gateway-icmp-ping-test") {
    $recommendation=$gatewayRecommendation
  }elseif ($check.metadata.name -like "http-connectivity-required-url-test") {
    $recommendation=$urlRecommendation
  }
  $testResults += [PSCustomObject]@{
    TestName=$check.metadata.name
    Outcome= $check.result.outcome
    Recommendation = $recommendation
  }
}

$testResults | Format-Table -Wrap -AutoSize

Saída de exemplo:

TestName                            Outcome Recommendation
--------                            ------- --------------
cloud-agent-connectivity-test       Success
gateway-icmp-ping-test              Success 
http-connectivity-required-url-test Failure Ensure that the logical network IP addresses have outbound internet access. If there's a firewall, ensure that AKS required URLs are accessible from Arc VM logical network.

Analise a saída do verificador de diagnóstico

A tabela a seguir fornece um resumo de cada teste realizado pelo script, incluindo possíveis causas de falha e recomendações para mitigação:

Nome do teste Descrição Causas do fracasso Recomendações de mitigação
teste de conectividade do agente na nuvem Verifica se o servidor DNS pode resolver o FQDN do agente de nuvem MOC e se o agente de nuvem está acessível a partir da VM do nó do plano de controle. O agente de nuvem é criado usando um dos endereços IP do pool de IP de gerenciamento, na porta 55000. A VM do nó do plano de controle recebe endereços IP da rede lógica Arc VM. Os endereços IP de rede lógica não podem se conectar aos endereços do pool de IP de gerenciamento devido a:
- Resolução incorreta do servidor DNS.
- Regras de firewall.
- A rede lógica está em uma vlan diferente do pool de IP de gerenciamento e não há conectividade cross-vlan.
Certifique-se de que os endereços IP da rede lógica podem se conectar a todos os endereços do pool de IP de gerenciamento nas portas necessárias. Verifique a porta de rede AKS e os requisitos de vlan cruzada para obter uma lista detalhada das portas que precisam ser abertas.
gateway-icmp-ping-teste Verifica se o gateway especificado na rede lógica conectada ao cluster AKS pode ser acessado a partir da VM do nó do plano de controle do cluster AKS. - O gateway está inativo ou inacessível.
- Problemas de roteamento de rede entre a VM do nó do plano de controle de cluster AKS e o gateway.
- Firewall bloqueando o tráfego ICMP.
- Garantir que o gateway está operacional.
- Verificar as configurações de roteamento.
- Ajuste as regras de firewall para permitir o tráfego ICMP.
http-conectividade-necessária-url-test Verifica se as URLs necessárias estão acessíveis a partir da VM do nó do plano de controle de cluster AKS. - A VM do nó do plano de controle não tem acesso à internet de saída.
- Os URLs necessários não são permitidos através do firewall.
Certifique-se de que os endereços IP da rede lógica têm acesso de saída à Internet. Se houver um firewall, certifique-se de que as URLs necessárias do AKS estejam acessíveis a partir da rede lógica Arc VM.

Próximos passos

Se o problema persistir, colete logs de cluster AKS antes de criar uma solicitação de suporte.