mirror of
https://github.com/volodymyrsmirnov/MalwareMultiScan.git
synced 2025-08-25 14:01:13 +00:00
refactoring, WiP
This commit is contained in:
85
MalwareMultiScan.Scanner/Services/ConsulHostedService.cs
Normal file
85
MalwareMultiScan.Scanner/Services/ConsulHostedService.cs
Normal file
@@ -0,0 +1,85 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Consul;
|
||||
using MalwareMultiScan.Backends.Backends.Interfaces;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace MalwareMultiScan.Scanner.Services
|
||||
{
|
||||
public class ConsulHostedService : BackgroundService
|
||||
{
|
||||
private static readonly string ServiceId = Dns.GetHostName();
|
||||
private static readonly string CheckId = $"ttl-{ServiceId}";
|
||||
|
||||
private readonly IConsulClient _consulClient;
|
||||
private readonly AgentServiceRegistration _registration;
|
||||
|
||||
public ConsulHostedService(
|
||||
IConsulClient consulClient,
|
||||
IConfiguration configuration,
|
||||
IScanBackend scanBackend)
|
||||
{
|
||||
_consulClient = consulClient;
|
||||
|
||||
_registration = new AgentServiceRegistration
|
||||
{
|
||||
ID = ServiceId,
|
||||
Name = configuration.GetValue<string>("CONSUL_SERVICE_NAME"),
|
||||
|
||||
Meta = new Dictionary<string, string>
|
||||
{
|
||||
{"BackendId", scanBackend.Id}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
await _consulClient.Agent.PassTTL(
|
||||
CheckId, string.Empty, stoppingToken);
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await _consulClient.Agent.ServiceDeregister(
|
||||
_registration.ID, cancellationToken);
|
||||
|
||||
await _consulClient.Agent.ServiceRegister(
|
||||
_registration, cancellationToken);
|
||||
|
||||
await _consulClient.Agent.CheckRegister(new AgentCheckRegistration
|
||||
{
|
||||
ID = CheckId,
|
||||
Name = "TTL",
|
||||
ServiceID = ServiceId,
|
||||
TTL = TimeSpan.FromSeconds(15),
|
||||
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(60)
|
||||
}, cancellationToken);
|
||||
|
||||
await base.StartAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await _consulClient.Agent.ServiceDeregister(
|
||||
_registration.ID, cancellationToken);
|
||||
|
||||
await _consulClient.Agent.CheckDeregister(
|
||||
CheckId, cancellationToken);
|
||||
|
||||
await base.StopAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user