mirror of
https://github.com/volodymyrsmirnov/MalwareMultiScan.git
synced 2025-08-23 21:12:22 +00:00
91 lines
2.9 KiB
C#
91 lines
2.9 KiB
C#
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.Hosting;
|
|
|
|
namespace MalwareMultiScan.Scanner.Services
|
|
{
|
|
/// <summary>
|
|
/// Consul registration hosted service.
|
|
/// </summary>
|
|
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;
|
|
|
|
/// <summary>
|
|
/// Initialize consul hosted service.
|
|
/// </summary>
|
|
/// <param name="consulClient">Consul client.</param>
|
|
/// <param name="scanBackend">Scan backend.</param>
|
|
public ConsulHostedService(
|
|
IConsulClient consulClient,
|
|
IScanBackend scanBackend)
|
|
{
|
|
_consulClient = consulClient;
|
|
|
|
_registration = new AgentServiceRegistration
|
|
{
|
|
ID = ServiceId,
|
|
Name = "scanner",
|
|
|
|
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);
|
|
}
|
|
}
|
|
} |