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("CONSUL_SERVICE_NAME"), Meta = new Dictionary { {"BackendId", scanBackend.Id} } }; } /// 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); } } /// 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); } /// public override async Task StopAsync(CancellationToken cancellationToken) { await _consulClient.Agent.ServiceDeregister( _registration.ID, cancellationToken); await _consulClient.Agent.CheckDeregister( CheckId, cancellationToken); await base.StopAsync(cancellationToken); } } }