mirror of
https://github.com/volodymyrsmirnov/MalwareMultiScan.git
synced 2025-10-11 04:26:16 +00:00
refactoring, documentation pending
This commit is contained in:
83
MalwareMultiScan.Scanner/Services/ScanHostedService.cs
Normal file
83
MalwareMultiScan.Scanner/Services/ScanHostedService.cs
Normal file
@@ -0,0 +1,83 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using EasyNetQ;
|
||||
using MalwareMultiScan.Backends.Interfaces;
|
||||
using MalwareMultiScan.Backends.Messages;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MalwareMultiScan.Scanner.Services
|
||||
{
|
||||
internal class ScanHostedService : IHostedService
|
||||
{
|
||||
private readonly IScanBackend _backend;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly ILogger<ScanHostedService> _logger;
|
||||
|
||||
private IBus _bus;
|
||||
|
||||
public ScanHostedService(ILogger<ScanHostedService> logger, IConfiguration configuration, IScanBackend backend)
|
||||
{
|
||||
_logger = logger;
|
||||
_configuration = configuration;
|
||||
_backend = backend;
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_bus = RabbitHutch.CreateBus(
|
||||
_configuration.GetConnectionString("RabbitMQ"));
|
||||
|
||||
_bus.Receive<ScanRequestMessage>(_backend.Id, Scan);
|
||||
|
||||
_logger.LogInformation(
|
||||
$"Started scan hosting service for the backend {_backend.Id}");
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_bus.Dispose();
|
||||
|
||||
_logger.LogInformation(
|
||||
$"Stopped scan hosting service for the backend {_backend.Id}");
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task Scan(ScanRequestMessage message)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
$"Starting scan of {message.Uri} via backend {_backend.Id} from {message.Id}");
|
||||
|
||||
var cancellationTokenSource = new CancellationTokenSource(
|
||||
TimeSpan.FromSeconds(_configuration.GetValue<int>("MaxScanningTime")));
|
||||
|
||||
try
|
||||
{
|
||||
var result = new ScanResultMessage
|
||||
{
|
||||
Id = message.Id,
|
||||
Backend = _backend.Id,
|
||||
|
||||
Threats = await _backend.ScanAsync(
|
||||
message.Uri, cancellationTokenSource.Token)
|
||||
};
|
||||
|
||||
_logger.LogInformation(
|
||||
$"Backend {_backend.Id} completed a scan of {message.Id} " +
|
||||
$"with result '{string.Join(", ", result.Threats)}'");
|
||||
|
||||
await _bus.SendAsync(_configuration.GetValue<string>("ResultsSubscriptionId"), result);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogError(
|
||||
exception, "Scanning failed with exception");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user