Volodymyr Smirnov cfcfe92784 code cleanup
2020-11-02 11:39:12 +02:00

102 lines
3.3 KiB
C#

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Hangfire;
using Hangfire.States;
using MalwareMultiScan.Backends.Backends.Interfaces;
using MalwareMultiScan.Shared.Enums;
using MalwareMultiScan.Shared.Message;
using MalwareMultiScan.Shared.Services.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace MalwareMultiScan.Scanner.Services
{
/// <inheritdoc />
public class ScanBackgroundJob : IScanBackgroundJob
{
private readonly IScanBackend _backend;
private readonly IConfiguration _configuration;
private readonly IBackgroundJobClient _jobClient;
private readonly ILogger<ScanBackgroundJob> _logger;
/// <summary>
/// Initialize scan background job.
/// </summary>
/// <param name="configuration">Configuration.</param>
/// <param name="logger">Logger.</param>
/// <param name="backend">Scan backend.</param>
/// <param name="jobClient">Background job client.</param>
public ScanBackgroundJob(
IScanBackend backend,
IConfiguration configuration,
ILogger<ScanBackgroundJob> logger,
IBackgroundJobClient jobClient)
{
_backend = backend;
_configuration = configuration;
_logger = logger;
_jobClient = jobClient;
}
/// <inheritdoc />
public async Task Process(ScanQueueMessage message)
{
_logger.LogInformation(
$"Starting scan of {message.Uri} via backend {_backend.Id} from {message.Id}");
var cancellationTokenSource = new CancellationTokenSource(
TimeSpan.FromSeconds(_configuration.GetValue<int>("MAX_SCANNING_TIME")));
var cancellationToken = cancellationTokenSource.Token;
var result = new ScanResultMessage
{
Status = ScanResultStatus.Queued
};
var stopwatch = new Stopwatch();
stopwatch.Start();
try
{
result.Threats = await _backend.ScanAsync(message.Uri, cancellationToken);
result.Status = ScanResultStatus.Succeeded;
_logger.LogInformation(
$"Backend {_backend.Id} completed a scan of {message.Id} " +
$"with result '{string.Join(", ", result.Threats)}'");
}
catch (Exception exception)
{
result.Status = ScanResultStatus.Failed;
_logger.LogError(
exception, "Scanning failed with exception");
}
finally
{
stopwatch.Stop();
}
result.Duration = stopwatch.ElapsedMilliseconds / 1000;
try
{
_logger.LogInformation(
$"Sending scan results with status {result.Status}");
_jobClient.Create<IScanResultJob>(
x => x.Report(message.Id, _backend.Id, result),
new EnqueuedState("default"));
}
catch (Exception exception)
{
_logger.LogError(exception, "Failed to send scan results");
}
}
}
}