Skip to content

Commit

Permalink
Health Checks for Background
Browse files Browse the repository at this point in the history
  • Loading branch information
phongnguyend committed Dec 5, 2024
1 parent 260b07f commit a7ec744
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 90 deletions.
23 changes: 5 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,7 @@
<summary><b>Message Broker</b></summary>

- Open below files and jump to **MessageBroker** section:
+ [ClassifiedAds.IdentityServer/appsettings.json](/src/Monolith/ClassifiedAds.IdentityServer/appsettings.json)
+ [ClassifiedAds.WebMVC/appsettings.json](/src/Monolith/ClassifiedAds.WebMVC/appsettings.json)
+ [ClassifiedAds.WebAPI/appsettings.json](/src/Monolith/ClassifiedAds.WebAPI/appsettings.json)
+ [ClassifiedAds.BackgroundServer/appsettings.json](/src/Monolith/ClassifiedAds.BackgroundServer/appsettings.json)
+ [ClassifiedAds.Background/appsettings.json](/src/Monolith/ClassifiedAds.Background/appsettings.json)
```js
"MessageBroker": {
"Provider": "RabbitMQ",
Expand Down Expand Up @@ -299,8 +296,7 @@
- Open and jump to **Logging** section of below files:
+ [ClassifiedAds.WebAPI/appsettings.json](/src/Monolith/ClassifiedAds.WebAPI/appsettings.json)
+ [ClassifiedAds.WebMVC/appsettings.json](/src/Monolith/ClassifiedAds.WebMVC/appsettings.json)
+ [ClassifiedAds.IdentityServer/appsettings.json](/src/Monolith/ClassifiedAds.IdentityServer/appsettings.json)
+ [ClassifiedAds.BackgroundServer/appsettings.json](/src/Monolith/ClassifiedAds.BackgroundServer/appsettings.json)
+ [ClassifiedAds.Background/appsettings.json](/src/Monolith/ClassifiedAds.Background/appsettings.json)
```js
"Logging": {
"LogLevel": {
Expand Down Expand Up @@ -381,7 +377,6 @@
- Open and jump to **Caching** section of below files:
+ [ClassifiedAds.WebAPI/appsettings.json](/src/Monolith/ClassifiedAds.WebAPI/appsettings.json)
+ [ClassifiedAds.WebMVC/appsettings.json](/src/Monolith/ClassifiedAds.WebMVC/appsettings.json)
+ [ClassifiedAds.IdentityServer/appsettings.json](/src/Monolith/ClassifiedAds.IdentityServer/appsettings.json)
```js
"Caching": {
"InMemory": {
Expand Down Expand Up @@ -448,7 +443,6 @@
- Open and jump to **Monitoring** section of below files:
+ [ClassifiedAds.WebAPI/appsettings.json](/src/Monolith/ClassifiedAds.WebAPI/appsettings.json)
+ [ClassifiedAds.WebMVC/appsettings.json](/src/Monolith/ClassifiedAds.WebMVC/appsettings.json)
+ [ClassifiedAds.IdentityServer/appsettings.json](/src/Monolith/ClassifiedAds.IdentityServer/appsettings.json)
```js
"Monitoring": {
"MiniProfiler": {
Expand Down Expand Up @@ -555,8 +549,7 @@
- Open and jump to **Interceptors** section of below files:
+ [ClassifiedAds.WebAPI/appsettings.json](/src/Monolith/ClassifiedAds.WebAPI/appsettings.json)
+ [ClassifiedAds.WebMVC/appsettings.json](/src/Monolith/ClassifiedAds.WebMVC/appsettings.json)
+ [ClassifiedAds.IdentityServer/appsettings.json](/src/Monolith/ClassifiedAds.IdentityServer/appsettings.json)
+ [ClassifiedAds.BackgroundServer/appsettings.json](/src/Monolith/ClassifiedAds.BackgroundServer/appsettings.json)
+ [ClassifiedAds.Background/appsettings.json](/src/Monolith/ClassifiedAds.Background/appsettings.json)
```js
"Interceptors": {
"LoggingInterceptor": true,
Expand Down Expand Up @@ -602,12 +595,6 @@
"AllowedOrigins": [ "http://localhost:4200", "http://localhost:3000", "http://localhost:8080" ]
},
```
- Open [ClassifiedAds.NotificationServer/appsettings.json](/src/Monolith/ClassifiedAds.NotificationServer/appsettings.json) and jump to **CORS** section:
```js
"CORS": {
"AllowedOrigins": [ "https://localhost:44364", "http://host.docker.internal:9003" ]
}
```
</details>

<details>
Expand Down Expand Up @@ -644,7 +631,7 @@
<details>
<summary><b>Sending Email</b></summary>

- Open [ClassifiedAds.BackgroundServer/appsettings.json](/src/Monolith/ClassifiedAds.BackgroundServer/appsettings.json) and jump to **Notification -> Email** section:
- Open [ClassifiedAds.Background/appsettings.json](/src/Monolith/ClassifiedAds.Background/appsettings.json) and jump to **Notification -> Email** section:
```js
"Notification": {
"Email": {
Expand Down Expand Up @@ -672,7 +659,7 @@
<details>
<summary><b>Sending SMS</b></summary>

- Open [ClassifiedAds.BackgroundServer/appsettings.json](/src/Monolith/ClassifiedAds.BackgroundServer/appsettings.json) and jump to **Notification -> Sms** section:
- Open [ClassifiedAds.Background/appsettings.json](/src/Monolith/ClassifiedAds.Background/appsettings.json) and jump to **Notification -> Sms** section:
```js
"Notification": {
"Sms": {
Expand Down
10 changes: 10 additions & 0 deletions src/Monolith/ClassifiedAds.Background/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using ClassifiedAds.Infrastructure.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using System.Reflection;

Expand Down Expand Up @@ -70,13 +71,22 @@
services.AddSingleton<IAzureActiveDirectoryB2CIdentityProvider>(new AzureActiveDirectoryB2CIdentityProvider(appSettings.IdentityProviders.AzureActiveDirectoryB2C));
}

services.AddHealthChecks()
.AddSqlServer(connectionString: appSettings.ConnectionStrings.ClassifiedAds,
healthQuery: "SELECT 1;",
name: "Sql Server",
failureStatus: HealthStatus.Degraded)
.AddMessageBusHealthCheck(appSettings.MessageBroker);

services.AddHostedService<MessageBusConsumerBackgroundService<WebhookConsumer, FileUploadedEvent>>();
services.AddHostedService<MessageBusConsumerBackgroundService<WebhookConsumer, FileDeletedEvent>>();
services.AddHostedService<PublishEventWorker>();
services.AddHostedService<SendEmailWorker>();
services.AddHostedService<SendSmsWorker>();
services.AddHostedService<ScheduleCronJobWorker>();
services.AddHostedService<SyncUsersWorker>();
services.AddHostedService<HealthChecksBackgroundService>();

})
.Build()
.Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace ClassifiedAds.Infrastructure.HostedServices;

public class HealthChecksBackgroundService : BackgroundService
{
private readonly IServiceProvider _services;
private readonly ILogger<HealthChecksBackgroundService> _logger;
private readonly HealthCheckService _healthCheckService;

public HealthChecksBackgroundService(IServiceProvider services,
ILogger<HealthChecksBackgroundService> logger,
HealthCheckService healthCheckService)
{
_services = services;
_logger = logger;
_healthCheckService = healthCheckService;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var jsonOptions = new JsonWriterOptions { Indented = true };

while (!stoppingToken.IsCancellationRequested)
{
var healthReport = await _healthCheckService.CheckHealthAsync(stoppingToken);

using var memoryStream = new MemoryStream();
using (var jsonWriter = new Utf8JsonWriter(memoryStream, jsonOptions))
{
jsonWriter.WriteStartObject();
jsonWriter.WriteString("status", healthReport.Status.ToString());
jsonWriter.WriteStartObject("results");

foreach (var healthReportEntry in healthReport.Entries)
{
jsonWriter.WriteStartObject(healthReportEntry.Key);
jsonWriter.WriteString("status", healthReportEntry.Value.Status.ToString());
jsonWriter.WriteString("description", healthReportEntry.Value.Description ?? healthReportEntry.Value.Exception?.Message.ToString());
jsonWriter.WriteStartObject("data");

foreach (var item in healthReportEntry.Value.Data)
{
jsonWriter.WritePropertyName(item.Key);

JsonSerializer.Serialize(jsonWriter, item.Value, item.Value?.GetType() ?? typeof(object));
}

jsonWriter.WriteEndObject();

jsonWriter.WriteEndObject();
}

jsonWriter.WriteEndObject();
jsonWriter.WriteEndObject();
}

var json = Encoding.UTF8.GetString(memoryStream.ToArray());

if (healthReport.Status == HealthStatus.Healthy)
{
_logger.LogInformation(json);
}
else if (healthReport.Status == HealthStatus.Degraded)
{
_logger.LogWarning(json);
}
else
{
_logger.LogError(json);
}

await Task.Delay(60_000, stoppingToken);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using ClassifiedAds.Infrastructure.Configuration;
using ClassifiedAds.Infrastructure.Interceptors;
using ClassifiedAds.Infrastructure.Logging;
using ClassifiedAds.Infrastructure.MessageBrokers;
using ClassifiedAds.Infrastructure.Monitoring;
using ClassifiedAds.Infrastructure.Storages;
using Microsoft.Extensions.Options;
Expand Down Expand Up @@ -34,8 +33,6 @@ public class AppSettings

public StorageOptions Storage { get; set; }

public MessageBrokerOptions MessageBroker { get; set; }

public CookiePolicyOptions CookiePolicyOptions { get; set; }

public Dictionary<string, string> SecurityHeaders { get; set; }
Expand Down
10 changes: 3 additions & 7 deletions src/Monolith/ClassifiedAds.WebMVC/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using ClassifiedAds.Application.FileEntries.DTOs;
using ClassifiedAds.CrossCuttingConcerns.Exceptions;
using ClassifiedAds.CrossCuttingConcerns.Exceptions;
using ClassifiedAds.Domain.Identity;
using ClassifiedAds.Infrastructure.Configuration;
using ClassifiedAds.Infrastructure.HealthChecks;
Expand Down Expand Up @@ -139,7 +138,7 @@

services.AddCaches(appSettings.Caching);

var healthChecksBuilder = services.AddHealthChecks()
services.AddHealthChecks()
.AddSqlServer(connectionString: appSettings.ConnectionStrings.ClassifiedAds,
healthQuery: "SELECT 1;",
name: "Sql Server",
Expand All @@ -150,8 +149,7 @@
.AddHttp(appSettings.ResourceServer.Endpoint,
name: "Resource (Web API) Server",
failureStatus: HealthStatus.Degraded)
.AddStorageManagerHealthCheck(appSettings.Storage)
.AddMessageBusHealthCheck(appSettings.MessageBroker);
.AddStorageManagerHealthCheck(appSettings.Storage);

services.AddHealthChecksUI(setupSettings: setup =>
{
Expand All @@ -163,8 +161,6 @@
services.AddScoped<ICurrentUser, CurrentWebUser>();

services.AddStorageManager(appSettings.Storage);
services.AddMessageBusSender<FileUploadedEvent>(appSettings.MessageBroker);
services.AddMessageBusSender<FileDeletedEvent>(appSettings.MessageBroker);

services.AddFeatureManagement();

Expand Down
54 changes: 0 additions & 54 deletions src/Monolith/ClassifiedAds.WebMVC/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -137,60 +137,6 @@
"RegionEndpoint": "ap-southeast-1"
}
},
"MessageBroker": {
"Provider": "Fake",
"RabbitMQ": {
"HostName": "localhost",
"UserName": "guest",
"Password": "guest",
"ExchangeName": "amq.direct",
"RoutingKeys": {
"FileUploadedEvent": "classifiedadds_fileuploaded",
"FileDeletedEvent": "classifiedadds_filedeleted"
},
"QueueNames": {
"FileUploadedEvent": "classifiedadds_fileuploaded",
"FileDeletedEvent": "classifiedadds_filedeleted"
}
},
"Kafka": {
"BootstrapServers": "localhost:9092",
"Topics": {
"FileUploadedEvent": "classifiedadds_fileuploaded",
"FileDeletedEvent": "classifiedadds_filedeleted"
},
"GroupId": "classified"
},
"AzureQueue": {
"ConnectionString": "DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx;EndpointSuffix=core.windows.net",
"QueueNames": {
"FileUploadedEvent": "classifiedadds-fileuploaded",
"FileDeletedEvent": "classifiedadds-filedeleted"
}
},
"AzureServiceBus": {
"ConnectionString": "Endpoint=sb://xxx.servicebus.windows.net/;SharedAccessKeyName=xxx;SharedAccessKey=xxx",
"QueueNames": {
"FileUploadedEvent": "classifiedadds_fileuploaded",
"FileDeletedEvent": "classifiedadds_filedeleted"
}
},
"AzureEventGrid": {
"DomainEndpoint": "https://xxx.xxx-1.eventgrid.azure.net/api/events",
"DomainKey": "xxxx",
"Topics": {
"FileUploadedEvent": "classifiedadds_fileuploaded",
"FileDeletedEvent": "classifiedadds_filedeleted"
}
},
"AzureEventHub": {
"ConnectionString": "Endpoint=sb://xxx.servicebus.windows.net/;SharedAccessKeyName=xxx;SharedAccessKey=xxx",
"Hubs": {
"FileUploadedEvent": "classifiedadds_fileuploaded",
"FileDeletedEvent": "classifiedadds_filedeleted"
}
}
},
"CookiePolicyOptions": {

},
Expand Down
8 changes: 0 additions & 8 deletions src/Monolith/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,6 @@ services:
Storage__Amazon__SecretAccessKey: ${Storage__Amazon__SecretAccessKey}
Storage__Amazon__BucketName: ${Storage__Amazon__BucketName}
Storage__Amazon__RegionEndpoint: ${Storage__Amazon__RegionEndpoint}
MessageBroker__Provider: ${MessageBroker__Provider}
MessageBroker__RabbitMQ__HostName: ${MessageBroker__RabbitMQ__HostName}
MessageBroker__Kafka__BootstrapServers: ${MessageBroker__Kafka__BootstrapServers}
MessageBroker__AzureQueue__ConnectionString: ${MessageBroker__AzureQueue__ConnectionString}
webmvc:
image: classifiedads.webmvc
build:
Expand Down Expand Up @@ -129,10 +125,6 @@ services:
Storage__Amazon__SecretAccessKey: ${Storage__Amazon__SecretAccessKey}
Storage__Amazon__BucketName: ${Storage__Amazon__BucketName}
Storage__Amazon__RegionEndpoint: ${Storage__Amazon__RegionEndpoint}
MessageBroker__Provider: ${MessageBroker__Provider}
MessageBroker__RabbitMQ__HostName: ${MessageBroker__RabbitMQ__HostName}
MessageBroker__Kafka__BootstrapServers: ${MessageBroker__Kafka__BootstrapServers}
MessageBroker__AzureQueue__ConnectionString: ${MessageBroker__AzureQueue__ConnectionString}
blazor:
image: classifiedads.blazor
build:
Expand Down

0 comments on commit a7ec744

Please sign in to comment.