This commit is contained in:
2024-10-11 23:10:01 -05:00
parent 4137ac9ad8
commit 62a4a47373
6 changed files with 173 additions and 0 deletions

View File

@@ -0,0 +1,39 @@
using Microsoft.Extensions.Logging;
namespace ProperDI.Azure.Endpoints.ResourceGroup.LogLooker;
public interface IActivityLogReader
{
Task Scan(CancellationToken cancellationToken);
}
public class ActivityLogReader : IActivityLogReader
{
private readonly ILogger<ActivityLogReader> _logger;
private readonly HttpClient _httpClient;
public ActivityLogReader(IHttpClientFactory httpClientFactory, ILogger<ActivityLogReader> logger)
{
_httpClient = httpClientFactory.CreateClient() ?? throw new ArgumentNullException(nameof(httpClientFactory));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task Scan(CancellationToken cancellationToken)
{
try
{
var response = await _httpClient.GetAsync("https://ident.me", cancellationToken);
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogInformation("Response body: {content}", responseBody);
}
catch (TaskCanceledException)
{
_logger.LogWarning("Task canceled");
}
catch (System.Exception ex)
{
_logger.LogError(ex, "Http request failed");
throw;
}
}
}

View File

@@ -0,0 +1,86 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ProperDI.Azure.Endpoints.ResourceGroup.LogLooker;
public class RoleAssesorBackgroundService : IHostedService, IDisposable
{
private readonly IActivityLogReader _activityLogReader;
private readonly ILogger<RoleAssesorBackgroundService> _logger;
private readonly IOptionsMonitor<RoleAssesorBackgroundServiceOptions> _options;
private Timer? _timer;
private int _runFrequencyInMinutes;
public RoleAssesorBackgroundService(
IActivityLogReader activityLogReader,
ILogger<RoleAssesorBackgroundService> logger,
IOptionsMonitor<RoleAssesorBackgroundServiceOptions> options)
{
_activityLogReader = activityLogReader;
_logger = logger;
_options = options;
// This sets our initial run frequency
_runFrequencyInMinutes = _options.CurrentValue.RunFrequencyInMinutes;
// Subscribe to any changes in the config file
_options.OnChange(UpdateTimerInterval);
}
private void UpdateTimerInterval(RoleAssesorBackgroundServiceOptions options)
{
var newFreq = options.RunFrequencyInMinutes;
if (newFreq == _runFrequencyInMinutes)
return;
_runFrequencyInMinutes = newFreq;
_logger.LogInformation("Run frequency updated to {RunFreq} minutes", _runFrequencyInMinutes);
_timer?.Change(TimeSpan.Zero, TimeSpan.FromMinutes(_runFrequencyInMinutes));
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Role Assessor background service is starting.");
_timer = new Timer(async _ => await ProcessAsync(cancellationToken), null, TimeSpan.Zero, TimeSpan.FromMinutes(1));
return Task.CompletedTask;
}
private async Task ProcessAsync(CancellationToken cancellationToken)
{
try
{
_logger.LogInformation("Role Assessor background service is running at: {time}", DateTimeOffset.Now);
if (cancellationToken.IsCancellationRequested)
return;
await _activityLogReader.Scan(cancellationToken);
}
catch (OperationCanceledException)
{
_logger.LogInformation("Operation was canceled");
}
catch (System.Exception ex)
{
_logger.LogError(ex, "An error occurred while reading the logs");
throw;
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Stopping the Role Assessor background service.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}

View File

@@ -0,0 +1,4 @@
public class RoleAssesorBackgroundServiceOptions
{
public int RunFrequencyInMinutes { get; set; } = 5; // Defaults to 5 minute.
}

15
Program.cs Normal file
View File

@@ -0,0 +1,15 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ProperDI.Azure.Endpoints.ResourceGroup.LogLooker;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHttpClient();
builder.Services.AddTransient<IActivityLogReader, ActivityLogReader>();
builder.Services.Configure<RoleAssesorBackgroundServiceOptions>(builder.Configuration.GetSection("RoleAssessorBackgroundService"));
builder.Services.AddHostedService<RoleAssesorBackgroundService>();
var host = builder.Build();
await host.RunAsync();

16
Sentinel.csproj Normal file
View File

@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" />
</ItemGroup>
</Project>

13
appsettings.json Normal file
View File

@@ -0,0 +1,13 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"System.Net": "Warning"
}
},
"RoleAssessorBackgroundService": {
"RunFrequencyInMinutes": 12
}
}