Comunicar e verificar o estado de funcionamento dos serviçosReport and check service health
Quando os serviços de encontram problemas, sua capacidade de responder a e corrigir incidentes e interrupções depende da sua capacidade de detetar os problemas rapidamente.When your services encounter problems, your ability to respond to and fix incidents and outages depends on your ability to detect the issues quickly. Se as reportar problemas e falhas para o Gestor de estado de funcionamento do Azure Service Fabric a partir do código de serviço, pode usar ferramentas que o Service Fabric fornece para verificar o estado de funcionamento de monitoramento de integridade padrão.If you report problems and failures to the Azure Service Fabric health manager from your service code, you can use standard health monitoring tools that Service Fabric provides to check the health status.
Existem três formas que pode comunicar o estado de funcionamento do serviço:There are three ways that you can report health from the service:
- Uso partição ou CodePackageActivationContext objetos.Use Partition or CodePackageActivationContext objects.
Pode utilizar oPartition
eCodePackageActivationContext
objetos para reportar o estado de funcionamento dos elementos que fazem parte do contexto atual.You can use thePartition
andCodePackageActivationContext
objects to report the health of elements that are part of the current context. Por exemplo, código que é executado como parte de uma réplica pode reportar o estado de funcionamento apenas nessa réplica, a partição que pertence a e a aplicação que é uma parte do.For example, code that runs as part of a replica can report health only on that replica, the partition that it belongs to, and the application that it is a part of. - Use
FabricClient
.UseFabricClient
.
Pode usarFabricClient
estado de funcionamento do relatório do código de serviço, se o cluster não estiver seguro ou se o serviço está em execução com privilégios de administrador.You can useFabricClient
to report health from the service code if the cluster is not secure or if the service is running with admin privileges. A maioria dos cenários do mundo real não utilizem clusters não seguros, ou fornecer privilégios de administrador.Most real-world scenarios do not use unsecured clusters, or provide admin privileges. ComFabricClient
, pode relatar estado de funcionamento em qualquer entidade que é uma parte do cluster.WithFabricClient
, you can report health on any entity that is a part of the cluster. O ideal é que, no entanto, o código de serviço só deve enviar relatórios relacionados com o seu próprio Estado de funcionamento.Ideally, however, service code should only send reports that are related to its own health. - Utilize as APIs REST no cluster, aplicação, aplicação implementada, serviço, o pacote de serviço, partição, réplica ou níveis de nó.Use the REST APIs at the cluster, application, deployed application, service, service package, partition, replica, or node levels. Isto pode ser utilizado para comunicar o estado de funcionamento de dentro de um contêiner.This can be used to report health from within a container.
Este artigo orienta-o num exemplo que reporte o estado de funcionamento do código de serviço.This article walks you through an example that reports health from the service code. O exemplo também mostra como as ferramentas fornecidas pelo Service Fabric podem ser utilizadas para verificar o estado de funcionamento.The example also shows how the tools provided by Service Fabric can be used to check the health status. Este artigo destina-se para ser uma introdução rápida para o estado de funcionamento monitorização de recursos do Service Fabric.This article is intended to be a quick introduction to the health monitoring capabilities of Service Fabric. Para obter informações mais detalhadas, leia a série de artigos detalhados sobre o estado de funcionamento que começam com a ligação no final deste artigo.For more detailed information, you can read the series of in-depth articles about health that start with the link at the end of this article.
Pré-requisitosPrerequisites
Tem de ter o seguinte instalado:You must have the following installed:
- Visual Studio 2015 ou Visual Studio 2019Visual Studio 2015 or Visual Studio 2019
- SDK do Service FabricService Fabric SDK
Para criar um cluster de desenvolvimento seguro localTo create a local secure dev cluster
- Abra o PowerShell com privilégios de administrador e execute os seguintes comandos:Open PowerShell with admin privileges, and run the following commands:
Para implementar uma aplicação e verificar o respetivo estado de funcionamentoTo deploy an application and check its health
Abra o Visual Studio como administrador.Open Visual Studio as an administrator.
Crie um projeto com o serviço com estado modelo.Create a project by using the Stateful Service template.
Prima F5 para executar a aplicação no modo de depuração.Press F5 to run the application in debug mode. A aplicação é implementada no cluster local.The application is deployed to the local cluster.
Depois da aplicação está em execução, clique com o botão direito no ícone do Gestor de clusters locais na área de notificação e selecione gerir Cluster Local no menu de atalho para abrir o Explorador de recursos de infraestrutura do serviço.After the application is running, right-click the Local Cluster Manager icon in the notification area and select Manage Local Cluster from the shortcut menu to open Service Fabric Explorer.
O estado de funcionamento do aplicativo deverá ser apresentado como esta imagem.The application health should be displayed as in this image. Neste momento, a aplicação deve estar em bom estado sem erros.At this time, the application should be healthy with no errors.
Também pode verificar o estado de funcionamento com o PowerShell.You can also check the health by using PowerShell. Pode usar
Get-ServiceFabricApplicationHealth
para verificar o estado de funcionamento de um aplicativo e pode usarGet-ServiceFabricServiceHealth
para verificar o estado de funcionamento de um serviço.You can useGet-ServiceFabricApplicationHealth
to check an application's health, and you can useGet-ServiceFabricServiceHealth
to check a service's health. O relatório de estado de funcionamento para a mesma aplicação no PowerShell é nesta imagem.The health report for the same application in PowerShell is in this image.
Adicionar eventos de estado de funcionamento personalizado ao seu código de serviçoTo add custom health events to your service code
Os modelos de projeto do Service Fabric no Visual Studio contêm código de exemplo.The Service Fabric project templates in Visual Studio contain sample code. Os passos seguintes mostram como pode comunicar os eventos de estado de funcionamento personalizados a partir do código de serviço.The following steps show how you can report custom health events from your service code. Esses relatórios aparecem automaticamente nas ferramentas padrão para monitorização de estado de funcionamento que o Service Fabric fornece, como o Service Fabric Explorer, a vista de estado de funcionamento de portal do Azure e PowerShell.Such reports show up automatically in the standard tools for health monitoring that Service Fabric provides, such as Service Fabric Explorer, Azure portal health view, and PowerShell.
Reabrir a aplicação que criou anteriormente no Visual Studio ou criar uma nova aplicação com o serviço com estado modelo do Visual Studio.Reopen the application that you created previously in Visual Studio, or create a new application by using the Stateful Service Visual Studio template.
Abra o ficheiro de Stateful1.cs e encontre a
myDictionary.TryGetValueAsync
chamar oRunAsync
método.Open the Stateful1.cs file, and find themyDictionary.TryGetValueAsync
call in theRunAsync
method. Pode ver que esse método retorna umresult
que contém o valor atual do contador de uma vez que a lógica de chave nesse aplicativo é manter uma contagem em execução.You can see that this method returns aresult
that holds the current value of the counter because the key logic in this application is to keep a count running. Se esta aplicação foi um aplicativo real, e se a falta de resultado representado uma falha, desejaria sinalizar que o evento.If this application was a real application, and if the lack of result represented a failure, you would want to flag that event.Para reportar um evento de estado de funcionamento quando a falta de resultado representa uma falha, adicione os seguintes passos.To report a health event when the lack of result represents a failure, add the following steps.
a.a. Adicionar o
System.Fabric.Health
espaço de nomes para o ficheiro de Stateful1.cs.Add theSystem.Fabric.Health
namespace to the Stateful1.cs file.using System.Fabric.Health;
b.b. Adicione o seguinte código após o
myDictionary.TryGetValueAsync
chamarAdd the following code after themyDictionary.TryGetValueAsync
callif (!result.HasValue) { HealthInformation healthInformation = new HealthInformation("ServiceCode", "StateDictionary", HealthState.Error); this.Partition.ReportReplicaHealth(healthInformation); }
Elaboramos relatórios de estado de funcionamento de réplica porque está a ser comunicado a partir de um serviço com estado.We report replica health because it's being reported from a stateful service. O
HealthInformation
parâmetro armazena informações sobre o problema de estado de funcionamento que está a ser comunicado.TheHealthInformation
parameter stores information about the health issue that's being reported.Se tiver criado um serviço sem estado, utilize o seguinte códigoIf you had created a stateless service, use the following code
if (!result.HasValue) { HealthInformation healthInformation = new HealthInformation("ServiceCode", "StateDictionary", HealthState.Error); this.Partition.ReportInstanceHealth(healthInformation); }
Se o seu serviço está em execução com privilégios de administrador ou se o cluster não estiver segura, também pode utilizar
FabricClient
para Estado de funcionamento do relatório conforme mostrado nas etapas a seguir.If your service is running with admin privileges or if the cluster is not secure, you can also useFabricClient
to report health as shown in the following steps.a.a. Criar a
FabricClient
instância depois dovar myDictionary
declaração.Create theFabricClient
instance after thevar myDictionary
declaration.var fabricClient = new FabricClient(new FabricClientSettings() { HealthReportSendInterval = TimeSpan.FromSeconds(0) });
b.b. Adicione o seguinte código após o
myDictionary.TryGetValueAsync
chamar.Add the following code after themyDictionary.TryGetValueAsync
call.if (!result.HasValue) { var replicaHealthReport = new StatefulServiceReplicaHealthReport( this.Context.PartitionId, this.Context.ReplicaId, new HealthInformation("ServiceCode", "StateDictionary", HealthState.Error)); fabricClient.HealthManager.ReportHealth(replicaHealthReport); }
Vamos simular esta falha e é exibido nas ferramentas de monitorização do Estado de funcionamento.Let's simulate this failure and see it show up in the health monitoring tools. Para simular a falha, comente a primeira linha no código de geração de relatórios de estado de funcionamento que adicionou anteriormente.To simulate the failure, comment out the first line in the health reporting code that you added earlier. Depois que comente a primeira linha, o código será a aparência semelhante ao seguinte exemplo.After you comment out the first line, the code will look like the following example.
//if(!result.HasValue) { HealthInformation healthInformation = new HealthInformation("ServiceCode", "StateDictionary", HealthState.Error); this.Partition.ReportReplicaHealth(healthInformation); }
Este código dispara o relatório de estado de funcionamento de cada vez
RunAsync
é executado.This code fires the health report each timeRunAsync
executes. Depois de efetuar a alteração, prima F5 para executar a aplicação.After you make the change, press F5 to run the application.Depois da aplicação está em execução, abra o Service Fabric Explorer para verificar o estado de funcionamento da aplicação.After the application is running, open Service Fabric Explorer to check the health of the application. Desta vez, Service Fabric Explorer mostra que a aplicação está danificada.This time, Service Fabric Explorer shows that the application is unhealthy. A aplicação mostra como mau estado de funcionamento porque o erro foi comunicado a partir do código que adicionamos anteriormente.The application shows as unhealthy because the error that was reported from the code that we added previously.
Se selecionar a réplica primária na vista de árvore do Service Fabric Explorer, verá que estado de funcionamento indica um erro, demasiado.If you select the primary replica in the tree view of Service Fabric Explorer, you will see that Health State indicates an error, too. Service Fabric Explorer também apresenta os detalhes do relatório de estado de funcionamento que foram adicionados para a
HealthInformation
parâmetro no código.Service Fabric Explorer also displays the health report details that were added to theHealthInformation
parameter in the code. Pode ver os relatórios de estado de funcionamento mesmo no PowerShell e o portal do Azure.You can see the same health reports in PowerShell and the Azure portal.
Este relatório permanece no Gestor de estado de funcionamento até que ele é substituído por outro relatório ou até que esta réplica seja eliminada.This report remains in the health manager until it is replaced by another report or until this replica is deleted. Uma vez que não definiu TimeToLive
para este relatório de estado de funcionamento no HealthInformation
de objeto, o relatório nunca expira.Because we did not set TimeToLive
for this health report in the HealthInformation
object, the report never expires.
Recomendamos que o estado de funcionamento deve ser informado sobre o nível mais granular, que neste caso é a réplica.We recommend that health should be reported on the most granular level, which in this case is the replica. Também pode comunicar o estado de funcionamento no Partition
.You can also report health on Partition
.
HealthInformation healthInformation = new HealthInformation("ServiceCode", "StateDictionary", HealthState.Error);
this.Partition.ReportPartitionHealth(healthInformation);
Para o estado de funcionamento do relatório no Application
, DeployedApplication
, e DeployedServicePackage
, utilize CodePackageActivationContext
.To report health on Application
, DeployedApplication
, and DeployedServicePackage
, use CodePackageActivationContext
.
HealthInformation healthInformation = new HealthInformation("ServiceCode", "StateDictionary", HealthState.Error);
var activationContext = FabricRuntime.GetActivationContext();
activationContext.ReportApplicationHealth(healthInformation);
Passos SeguintesNext steps
- Descrição detalhada da integridade do Service FabricDeep dive on Service Fabric health
- API REST para geração de relatórios de estado de funcionamento do serviçoREST API for reporting service health
- API REST para geração de relatórios de estado de funcionamento da aplicaçãoREST API for reporting application health
Comentários
A carregar comentários...