Nota
O acesso a esta página requer autorização. Pode tentar iniciar sessão ou alterar os diretórios.
O acesso a esta página requer autorização. Pode tentar alterar os diretórios.
Aplica-se a: SQL Server
Este artigo descreve formas de identificar extensões pouco saudáveis que não estão instaladas corretamente, a funcionar corretamente ou que não estão ligadas ao Azure.
Identificar extensões prejudiciais
Use o painel de saúde da extensão integrado no portal do Azure
Pode usar o painel de saúde da extensão incorporado no portal Azure para mostrar a saúde de todas as extensões Azure implementadas para SQL Server.
Dica
Crie o seu próprio painel personalizado com este ficheiro a partir do repositório GitHub sql-server-samples: Arc-enabled SQL Server Health.json.
Consultar extensões não saudáveis usando o Azure Resource Graph
Use o Azure Resource Graph para identificar o estado da extensão Azure para SQL Server nos seus servidores habilitados pelo Azure Arc.
Dica
Se ainda não conheces, aprende sobre o Azure Resource Graph:
Esta consulta devolve instâncias de SQL Server em servidores com extensões instaladas, mas que não são saudáveis.
resources
| where type == "microsoft.hybridcompute/machines/extensions"
| where properties.type in ("WindowsAgent.SqlServer", "LinuxAgent.SqlServer")
| extend targetMachineName = tolower(tostring(split(id, '/')[8])) // Extract the machine name from the extension's id
| join kind=leftouter (
resources
| where type == "microsoft.hybridcompute/machines"
| project machineId = id, MachineName = name, subscriptionId, LowerMachineName = tolower(name), resourceGroup , MachineStatus= properties.status , MachineProvisioningStatus= properties.provisioningState, MachineErrors = properties.errorDetails //Project relevant machine health information.
) on $left.targetMachineName == $right.LowerMachineName and $left.resourceGroup == $right.resourceGroup and $left.subscriptionId == $right.subscriptionId // Join Based on MachineName in the id and the machine's name, the resource group, and the subscription. This join allows us to present the data of the machine as well as the extension in the final output.
| extend statusExpirationLengthRange = 3d // Change this value to change the acceptable range for the last time an extension should have reported its status.
| extend startDate = startofday(now() - statusExpirationLengthRange), endDate = startofday(now()) // Get the start and end position for the given range.
| extend extractedDateString = extract("timestampUTC : (\\d{4}\\W\\d{2}\\W\\d{2})", 1, tostring(properties.instanceView.status.message)) // Extracting the date string for the LastUploadTimestamp. Is empty if none is found.
| extend extractedDateStringYear = split(extractedDateString, '/')[0], extractedDateStringMonth = split(extractedDateString, '/')[1], extractedDateStringDay = split(extractedDateString, '/')[2] // Identifying each of the parts of the date that was extracted from the message.
| extend extractedDate = todatetime(strcat(extractedDateStringYear,"-",extractedDateStringMonth,"-",extractedDateStringDay,"T00:00:00Z")) // Converting to a datetime object and rewriting string into ISO format because todatetime() does not work using the previous format.
| extend isNotInDateRange = not(extractedDate >= startDate and extractedDate <= endDate) // Created bool which is true if the date we extracted from the message is not within the specified range. This bool will also be true if the date was not found in the message.
| where properties.instanceView.status.message !contains "SQL Server Extension Agent: Healthy" // Begin searching for unhealthy extensions using the following 1. Does extension report being healthy. 2. Is last upload within the given range. 3. Is the upload status in an OK state. 4. Is provisioning state not in a succeeded state.
or isNotInDateRange
or properties.instanceView.status.message !contains "uploadStatus : OK"
or properties.provisioningState != "Succeeded"
or MachineStatus != "Connected"
| extend FailureReasons = strcat( // Makes a String to list all the reason that this resource got flagged for
iif(MachineStatus != "Connected",strcat("- Machine's status is ", MachineStatus," -"),"") ,
iif(MachineErrors != "[]","- Machine reports errors -", ""),
iif(properties.instanceView.status.message !contains "SQL Server Extension Agent: Healthy","- Extension reported unhealthy -",""),
iif(isNotInDateRange,"- Last upload outside acceptable range -",""),
iif(properties.instanceView.status.message !contains "uploadStatus : OK","- Upload status is not reported OK -",""),
iif(properties.provisioningState != "Succeeded",strcat("- Extension provisiong state is ", properties.provisioningState," -"),"")
)
| extend RecommendedAction = //Attempt to Identify RootCause based on information gathered, and point customer to what they should investigate first.
iif(MachineStatus == "Disconnected", "Machine is disconnected. Please reconnect the machine.",
iif(MachineStatus == "Expired", "Machine cert is expired. Go to the machine on the Azure portal for more information on how to resolve this issue.",
iif(MachineStatus != "Connected", strcat("Machine status is ", MachineStatus,". Investigate and resolve this issue."),
iif(MachineProvisioningStatus != "Succeeded", strcat("Machine provisioning status is ", MachineProvisioningStatus, ". Investigate and resolve machine provisioning status"),
iff(MachineErrors != "[]", "Machine is reporting errors. Investigate and resolve machine errors",
iif(properties.provisioningState != "Succeeded", strcat("Extension provisioning status is ", properties.provisioningState,". Investigate and resolve extension provisioning state."),
iff(properties.instanceView.status.message !contains "SQL Server Extension Agent:" and properties.instanceView.status.message contains "SQL Server Extension Agent Deployer", "SQL Server extension employer ran. However, SQL Server extension seems to not be running. Verify that the extension is currently running.",
iff(properties.instanceView.status.message !contains "uploadStatus : OK" or isNotInDateRange or properties.instanceView.status.message !contains "SQL Server Extension Agent: Healthy", "Extension reported as unhealthy. View FailureReasons and LastExtensionStatusMessage for more information as to the cause of the failure.",
"Unable to recommend actions. Please view FailureReasons."
)
)
)
)
)
)
)
)
| project ID = id, MachineName, ResourceGroup = resourceGroup, SubscriptionID = subscriptionId, Location = location, RecommendedAction, FailureReasons, LicenseType = properties.settings.LicenseType,
LastReportedExtensionHealth = iif(properties.instanceView.status.message !contains "SQL Server Extension Agent: Healthy", "Unhealthy", "Healthy"),
LastExtensionUploadTimestamp = iif(indexof(properties.instanceView.status.message, "timestampUTC : ") > 0,
substring(properties.instanceView.status.message, indexof(properties.instanceView.status.message, "timestampUTC : ") + 15, 10),
"no timestamp"),
LastExtensionUploadStatus = iif(indexof(properties.instanceView.status.message, "uploadStatus : OK") > 0, "OK", "Unhealthy"),
ExtensionProvisioningState = properties.provisioningState,
MachineStatus, MachineErrors, MachineProvisioningStatus,MachineId = machineId,
LastExtensionStatusMessage = properties.instanceView.status.message
Para identificar possíveis problemas, reveja o valor na coluna RecommendedAction ou na coluna FailureReasons. A coluna RecommendedAction fornece possíveis primeiros passos para resolver o problema ou pistas sobre o que verificar primeiro. A coluna FailureReasons lista os motivos pelos quais o recurso foi considerado não saudável. Finalmente, verifique LastExtensionStatusMessage para ver a última mensagem relatada pelo agente.
Recomendações
| Ação Recomendada | Detalhes da ação |
|---|---|
| O certificado da máquina expirou. Consulte a máquina no portal do Azure para mais informações sobre como resolver este problema. |
A máquina compatível com Arc tem de ser reintegrada no Arc porque o certificado usado para autenticar no Azure expirou. O estado da máquina Arc é Expirado no portal Azure. Podes desinstalar o agente e depois voltar a instalar. Não há necessidade de apagar os recursos do SQL Server com Arc no portal se estiveres a reintegrar. A extensão SQL é instalada automaticamente novamente, contanto que a integração automática esteja habilitada (padrão). |
| A máquina está desconectada. Reconecte a máquina. |
A máquina Arc está em uma state = Disconnected. Este estado pode ser por várias razões:O agente da máquina conectado ao Arc está parado, desativado ou constantemente a falhar. ou A conectividade está bloqueada entre o agente e o Azure. Verifique o estado dos serviços/daemons da máquina conectada ao Arc para garantir que eles estejam habilitados e em execução. Verifique a conectividade. Solucione problemas do agente usando o log detalhado. |
| Extensão relatada como insalubre. Exiba FailureReasons e LastExtensionStatusMessage para obter mais informações sobre a causa da falha. Último carregamento fora do intervalo aceitável (nos últimos três dias). |
Verifique a coluna LastExtensionUploadTimestamp. Se for Sem marca temporal, nunca reportou dados de inventário ou uso para o Azure.
Solucione problemas de conectividade com o serviço de processamento de dados e endpoints de telemetria. Se o último upload estiver fora do intervalo aceitável (nos últimos três dias) e tudo o resto parecer normal, como LastExtensionUploadStatus, ExtensionProvisioningState e MachineStatus, então é possível que a extensão Azure para SQL Server serviço/daemon seja interrompida. Descubra por que ele está parado e inicie-o novamente. Verifique o LastExtensionStatusMessage para obter outras pistas sobre o problema. |
| O status de provisionamento de extensão é Falhou. Investigue e resolva o estado de provisionamento de extensão. |
Ou a instalação inicial ou a atualização da extensão SQL falhou.Solucionar problemas com a implementação da extensão do servidor SQL no Azure. Verifique o valor em LastExtensionStatusMessage. |
| O status do carregamento não é reportado como OK | Verifique a coluna LastExtensionMessage no painel e veja o valor de uploadStatus e o valor de uploadMessage (se presente, dependendo da versão). O valor do uploadStatus é normalmente um código de erro HTTP. Consulte Solucionar problemas de códigos de erro. O uploadMessage pode ter informações mais específicas. Solucione problemas de conectividade com o serviço de processamento de dados e endpoints de telemetria. |
| O status de provisionamento de extensão é Atualização ou O estado de provisionamento de extensão está criando ou O estado de provisionamento de extensão é Falhado ou O estado de provisionamento de extensão é Excluindo |
Se uma determinada extensão permanecer em um destes estados por mais de 30 minutos, é provável que haja um problema com o aprovisionamento. Desinstale a extensão e reinstale-a usando a CLI ou o portal. Se o problema persistir, verifique o implantador e os logs de extensão. Se a criação da extensão falhar, verifique se o agente está conectado e se os serviços de agente associados estão em execução. Se a exclusão falhar, tente desinstalar o agente e excluir o recurso da máquina Arc no portal, se necessário, e reimplante. Podes desinstalar o agente e depois voltar a instalar. |
Identificar extensão não saudável (PowerShell)
Este exemplo é executado no PowerShell. O exemplo retorna o mesmo resultado da consulta anterior, mas por meio de um script do PowerShell.
# PowerShell script to execute an Azure Resource Graph query using Azure CLI
# where the extension status is unhealthy or the extension last upload time isn't in this month or the previous month.
# Requires the Az.ResourceGraph PowerShell module
# Login to Azure if needed
#az login
# Define the Azure Resource Graph query
$query = @"
resources
| where type == "microsoft.hybridcompute/machines/extensions"
| where properties.type in ("WindowsAgent.SqlServer", "LinuxAgent.SqlServer")
| extend targetMachineName = tolower(tostring(split(id, '/')[8])) // Extract the machine name from the extension's id
| join kind=leftouter (
resources
| where type == "microsoft.hybridcompute/machines"
| project machineId = id, MachineName = name, subscriptionId, LowerMachineName = tolower(name), resourceGroup , MachineStatus= properties.status , MachineProvisioningStatus= properties.provisioningState, MachineErrors = properties.errorDetails //Project relevant machine health information.
) on $left.targetMachineName == $right.LowerMachineName and $left.resourceGroup == $right.resourceGroup and $left.subscriptionId == $right.subscriptionId // Join Based on MachineName in the id and the machine's name, the resource group, and the subscription. This join allows us to present the data of the machine as well as the extension in the final output.
| extend statusExpirationLengthRange = 3d // Change this value to change the acceptable range for the last time an extension should have reported its status.
| extend startDate = startofday(now() - statusExpirationLengthRange), endDate = startofday(now()) // Get the start and end position for the given range.
| extend extractedDateString = extract("timestampUTC : (\\d{4}\\W\\d{2}\\W\\d{2})", 1, tostring(properties.instanceView.status.message)) // Extracting the date string for the LastUploadTimestamp. Is empty if none is found.
| extend extractedDateStringYear = split(extractedDateString, '/')[0], extractedDateStringMonth = split(extractedDateString, '/')[1], extractedDateStringDay = split(extractedDateString, '/')[2] // Identifying each of the parts of the date that was extracted from the message.
| extend extractedDate = todatetime(strcat(extractedDateStringYear,"-",extractedDateStringMonth,"-",extractedDateStringDay,"T00:00:00Z")) // Converting to a datetime object and rewriting string into ISO format because todatetime() does not work using the previous format.
| extend isNotInDateRange = not(extractedDate >= startDate and extractedDate <= endDate) // Created bool which is true if the date we extracted from the message is not within the specified range. This bool will also be true if the date was not found in the message.
| where properties.instanceView.status.message !contains "SQL Server Extension Agent: Healthy" // Begin searching for unhealthy extensions using the following 1. Does extension report being healthy. 2. Is last upload within the given range. 3. Is the upload status in an OK state. 4. Is provisioning state not in a succeeded state.
or isNotInDateRange
or properties.instanceView.status.message !contains "uploadStatus : OK"
or properties.provisioningState != "Succeeded"
or MachineStatus != "Connected"
| extend FailureReasons = strcat( // Makes a String to list all the reason that this resource got flagged for
iif(MachineStatus != "Connected",strcat("- Machine's status is ", MachineStatus," -"),"") ,
iif(MachineErrors != "[]","- Machine reports errors -", ""),
iif(properties.instanceView.status.message !contains "SQL Server Extension Agent: Healthy","- Extension reported unhealthy -",""),
iif(isNotInDateRange,"- Last upload outside acceptable range -",""),
iif(properties.instanceView.status.message !contains "uploadStatus : OK","- Upload status is not reported OK -",""),
iif(properties.provisioningState != "Succeeded",strcat("- Extension provisiong state is ", properties.provisioningState," -"),"")
)
| extend RecommendedAction = //Attempt to Identify RootCause based on information gathered, and point customer to what they should investigate first.
iif(MachineStatus == "Disconnected", "Machine is disconnected. Please reconnect the machine.",
iif(MachineStatus == "Expired", "Machine cert is expired. Go to the machine on the Azure portal for more information on how to resolve this issue.",
iif(MachineStatus != "Connected", strcat("Machine status is ", MachineStatus,". Investigate and resolve this issue."),
iif(MachineProvisioningStatus != "Succeeded", strcat("Machine provisioning status is ", MachineProvisioningStatus, ". Investigate and resolve machine provisioning status"),
iff(MachineErrors != "[]", "Machine is reporting errors. Investigate and resolve machine errors",
iif(properties.provisioningState != "Succeeded", strcat("Extension provisioning status is ", properties.provisioningState,". Investigate and resolve extension provisioning state."),
iff(properties.instanceView.status.message !contains "SQL Server Extension Agent:" and properties.instanceView.status.message contains "SQL Server Extension Agent Deployer", "SQL Server extension employer ran. However, SQL Server extension seems to not be running. Verify that the extension is currently running.",
iff(properties.instanceView.status.message !contains "uploadStatus : OK" or isNotInDateRange or properties.instanceView.status.message !contains "SQL Server Extension Agent: Healthy", "Extension reported as unhealthy. View FailureReasons and LastExtensionStatusMessage for more information as to the cause of the failure.",
"Unable to recommend actions. Please view FailureReasons."
)
)
)
)
)
)
)
)
| project ID = id, MachineName, ResourceGroup = resourceGroup, SubscriptionID = subscriptionId, Location = location, RecommendedAction, FailureReasons, LicenseType = properties.settings.LicenseType,
LastReportedExtensionHealth = iif(properties.instanceView.status.message !contains "SQL Server Extension Agent: Healthy", "Unhealthy", "Healthy"),
LastExtensionUploadTimestamp = iif(indexof(properties.instanceView.status.message, "timestampUTC : ") > 0,
substring(properties.instanceView.status.message, indexof(properties.instanceView.status.message, "timestampUTC : ") + 15, 10),
"no timestamp"),
LastExtensionUploadStatus = iif(indexof(properties.instanceView.status.message, "uploadStatus : OK") > 0, "OK", "Unhealthy"),
ExtensionProvisioningState = properties.provisioningState,
MachineStatus, MachineErrors, MachineProvisioningStatus,MachineId = machineId,
LastExtensionStatusMessage = properties.instanceView.status.message
"@
# Execute the Azure Resource Graph query
$result = Search-AzGraph -Query $query
# Output the results
$result | Format-Table -Property ExtensionHealth, LastUploadTimestamp, LastUploadStatus, Message
Para identificar possíveis problemas, reveja o valor na coluna RecommendedAction ou na coluna FailureReasons. A coluna RecommendedAction fornece possíveis primeiros passos para resolver o problema ou pistas sobre o que verificar primeiro. A coluna FailureReasons lista os motivos pelos quais o recurso foi considerado não saudável. Finalmente, verifique LastExtensionStatusMessage para ver a última mensagem relatada pelo agente.
Identificar extensões que faltam atualizações
Identifique extensões sem atualizações de status recentes. Esta consulta devolve uma lista de extensões do Azure para SQL Server ordenadas pelo número de dias desde que a extensão atualizou o seu estado pela última vez. Um valor de '-1' indica que a extensão falhou e há um stack de chamadas no estado da extensão.
// Show the timestamp extracted
// If an extension has crashed (i.e. no heartbeat), fill timestamp with "1900/01/01, 00:00:00.000"
//
resources
| where type =~ 'microsoft.hybridcompute/machines/extensions'
| extend extensionStatus = parse_json(properties).instanceView.status.message
| extend timestampExtracted = extract(@"timestampUTC\s*:\s*(\d{4}/\d{2}/\d{2}, \d{2}:\d{2}:\d{2}\.\d{3})", 1, tostring(extensionStatus))
| extend timestampNullFilled = iff(isnull(timestampExtracted) or timestampExtracted == "", "1900/01/01, 00:00:00.000", timestampExtracted)
| extend timestampKustoFormattedString = strcat(replace(",", "", replace("/", "-", replace("/", "-", timestampNullFilled))), "Z")
| extend agentHeartbeatUtcTimestamp = todatetime(timestampKustoFormattedString)
| extend agentHeartbeatLagInDays = datetime_diff('day', now(), agentHeartbeatUtcTimestamp)
| project id, extensionStatus, agentHeartbeatUtcTimestamp, agentHeartbeatLagInDays
| limit 100
| order by ['agentHeartbeatLagInDays'] asc
Esta consulta retorna uma contagem de extensões agrupadas pelo número de dias desde a última atualização de status da extensão. Um valor de '-1' indica que a extensão falhou e há um stack de chamadas no estado da extensão.
// Aggregate by timestamp
//
// -1: Crashed extension with no heartbeat, we got a stacktrace instead
// 0: Healthy
// >1: Stale/Offline
//
resources
| where type =~ 'microsoft.hybridcompute/machines/extensions'
| extend extensionStatus = parse_json(properties).instanceView.status.message
| extend timestampExtracted = extract(@"timestampUTC\s*:\s*(\d{4}/\d{2}/\d{2}, \d{2}:\d{2}:\d{2}\.\d{3})", 1, tostring(extensionStatus))
| extend timestampNullFilled = iff(isnull(timestampExtracted) or timestampExtracted == "", "1900/01/01, 00:00:00.000", timestampExtracted)
| extend timestampKustoFormattedString = strcat(replace(",", "", replace("/", "-", replace("/", "-", timestampNullFilled))), "Z")
| extend agentHeartbeatUtcTimestamp = todatetime(timestampKustoFormattedString)
| extend agentHeartbeatLagInDays = iff(agentHeartbeatUtcTimestamp == todatetime("1900/01/01, 00:00:00.000Z"), -1, datetime_diff('day', now(), agentHeartbeatUtcTimestamp))
| summarize numExtensions = count() by agentHeartbeatLagInDays
| order by numExtensions desc
Recurso eliminado ainda aparece no portal do Azure
Observação
Depois de delete um recurso SQL Server - Azure Arc, o recurso pode continuar a aparecer no portal Azure durante algum tempo. Este comportamento é esperado e é causado pela cache do Azure Resource Manager. O recurso normalmente desaparece após a atualização da cache. Se o recurso continuar a aparecer após várias horas, pode verificar que foi eliminado com sucesso consultando o Azure Resource Graph ou usando a CLI do Azure. Não é necessária mais nenhuma ação — o recurso não está funcional e não sofre cargas após a eliminação.
Melhorar a extensão
Para determinar a versão da versão atual da extensão, consulte as notas de lançamento.
Para verificar a versão da sua extensão, use o seguinte comando PowerShell:
azcmagent version
Para simplificar as atualizações das extensões, certifique-se de ativar as atualizações automáticas. Também pode atualizar manualmente a extensão usando o portal Azure, PowerShell e a CLI do Azure.
Para atualizar a extensão no portal Azure, siga estes passos:
No portal Azure, vai a Máquinas - Azure Arc.
Selecione o nome da máquina onde SQL Server está instalado para abrir o painel Visão Geral do seu servidor.
Em Configurações, selecione Extensões.
Assinala a caixa da
WindowsAgent.SqlServerextensão e depois seleciona Atualizar no menu de navegação.
Selecione Sim na caixa de confirmação Atualizar extensão para completar a atualização.
Para mais informações sobre a atualização da extensão Azure para SQL Server, veja Upgrade extension.