163 lines
5.8 KiB
C#
163 lines
5.8 KiB
C#
/* This software is licensed by the MIT License, see LICENSE file */
|
|
/* Copyright © 2024-2025 Gregory Lirent */
|
|
|
|
using Microsoft.Extensions.Options;
|
|
using System.Collections.Generic;
|
|
using System.Runtime.Versioning;
|
|
using WebmrAPI.Configuration;
|
|
using WebmrAPI.Exceptions;
|
|
using WebmrAPI.Models;
|
|
using WebmrAPI.Services.Scanners;
|
|
using WebmrAPI.Utils;
|
|
|
|
namespace WebmrAPI.Services
|
|
{
|
|
[SupportedOSPlatform("windows")]
|
|
public class ProcessMonitor : BackgroundService
|
|
{
|
|
private readonly ILogger<ProcessMonitor> _logger;
|
|
private readonly MonitoringSettings _config;
|
|
private LazyConcurrentContainer<ProcessInfo> _processes = new();
|
|
private LazyConcurrentContainer<WindowInfo> _windows = new();
|
|
private ScanProvider _provider;
|
|
|
|
public ILogger<ProcessMonitor> Logger { get => _logger; }
|
|
public MonitoringSettings Config { get => _config; }
|
|
public LazyConcurrentContainer<ProcessInfo> Processes { get => _processes; }
|
|
public LazyConcurrentContainer<WindowInfo> Windows { get => _windows; }
|
|
|
|
public IEnumerable<ProcessBaseInfo>? GetBufferedProcesses()
|
|
{
|
|
return _processes.Values;
|
|
}
|
|
public IEnumerable<WindowInfo>? GetBufferedWindows()
|
|
{
|
|
return _windows.Values;
|
|
}
|
|
|
|
async public Task<ProcessInfo?> GetProcessDetails(int pid, ScanTarget target = ScanTarget.ProcessDetails)
|
|
{
|
|
if (_processes.Container != null && _processes.Container.TryGetValue(pid, out var info))
|
|
{
|
|
try
|
|
{
|
|
await _provider.CreateScanTask(info, target).ScanAsync();
|
|
_logger.LogInformation($"Scan details of the process {info.Name} (PID: {info.PID}) was completed.");
|
|
return info;
|
|
}
|
|
catch (ProcessMonitorException ex)
|
|
{
|
|
_logger.LogWarning(ex.Message);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError($"Unhandled error during scanning of the process {info.Name} (PID: {info.PID}): {ex.Message}");
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
public Task<IEnumerable<BaseWindowInfo>?> GetProcessWindows(int pid)
|
|
{
|
|
return Task.Run(() =>
|
|
{
|
|
if (_processes.Container != null && _processes.Container.TryGetValue(pid, out var info))
|
|
{
|
|
return info.Windows;
|
|
}
|
|
|
|
return null;
|
|
});
|
|
}
|
|
|
|
public ProcessMonitor(ILogger<ProcessMonitor> logger, IOptions<AppSettings> settings)
|
|
{
|
|
_logger = logger;
|
|
_config = settings.Value.Monitoring;
|
|
_provider = new(this);
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
_logger.LogInformation($"ProcessMonitor started. Scan interval: {_config.ProcessScanInterval} seconds.");
|
|
|
|
await ScanAsync();
|
|
|
|
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(_config.ProcessScanInterval));
|
|
try
|
|
{
|
|
while (await timer.WaitForNextTickAsync(stoppingToken))
|
|
{
|
|
await ScanAsync();
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
_logger.LogInformation("ProcessMonitor is stopping due to cancellation.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "ProcessMonitor encountered an unhandled exception and is stopping.");
|
|
}
|
|
}
|
|
|
|
private async Task ScanAsync()
|
|
{
|
|
_logger.LogDebug("Initiating process scan...");
|
|
try
|
|
{
|
|
await _provider.CreateScanTask().ScanAsync();
|
|
await new WindowScanner(_provider, _windows).ScanAsync();
|
|
|
|
Dictionary<int, List<BaseWindowInfo>> pWin = new();
|
|
Dictionary<int, List<BaseWindowInfo>> tWin = new();
|
|
|
|
if (_windows.Values != null)
|
|
foreach (var window in _windows.Values)
|
|
{
|
|
List<BaseWindowInfo> p;
|
|
List<BaseWindowInfo> t;
|
|
if (!pWin.TryGetValue(window.PID, out p))
|
|
{
|
|
pWin.Add(window.PID, p = new());
|
|
}
|
|
if (!tWin.TryGetValue(window.ThreadId, out t))
|
|
{
|
|
tWin.Add(window.ThreadId, t = new());
|
|
}
|
|
|
|
p.Add(window);
|
|
t.Add(window);
|
|
}
|
|
|
|
if (_processes.Values != null)
|
|
foreach (var proc in _processes.Values)
|
|
{
|
|
if (pWin.TryGetValue(proc.PID, out var pws))
|
|
{
|
|
proc.Windows = pws;
|
|
if (proc.ThreadsContainer.Values != null)
|
|
foreach (var thread in proc.ThreadsContainer.Values)
|
|
{
|
|
if (tWin.TryGetValue(thread.ID, out var tws))
|
|
{
|
|
thread.Windows = tws;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
_logger.LogInformation($"Process buffer updated, contains {Processes.Container?.Count} processes.");
|
|
}
|
|
catch (ProcessMonitorException ex)
|
|
{
|
|
_logger.LogWarning(ex.Message);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError($"Unhandled error during process monitoring cycle: {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
}
|