/* * ThreadPilot - Advanced Windows Process and Power Plan Manager * Copyright (C) 2025 Prime Build * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using ThreadPilot.Models; namespace ThreadPilot.Services { /// /// Main orchestration service that coordinates process monitoring and power plan management /// public class ProcessMonitorManagerService : IProcessMonitorManagerService { private readonly IProcessMonitorService _processMonitorService; private readonly IProcessPowerPlanAssociationService _associationService; private readonly IPowerPlanService _powerPlanService; private readonly INotificationService _notificationService; private readonly IApplicationSettingsService _settingsService; private readonly IProcessService _processService; private readonly ICoreMaskService _coreMaskService; private readonly ILogger _logger; private readonly IEnhancedLoggingService _enhancedLogger; private readonly object _lockObject = new(); private readonly ConcurrentDictionary _runningAssociatedProcesses = new(); private readonly System.Threading.Timer _delayTimer; private readonly SemaphoreSlim _powerPlanChangeSemaphore = new(1, 1); private readonly SemaphoreSlim _stateMutationSemaphore = new(1, 1); private bool _isRunning; private string _status = "Stopped"; private bool _disposed; private ProcessMonitorConfiguration? _configuration; private int _pendingPowerPlanReevaluation; public event EventHandler? ProcessPowerPlanChanged; public event EventHandler? ServiceStatusChanged; public bool IsRunning => _isRunning; public string Status => _status; public IEnumerable RunningAssociatedProcesses => _runningAssociatedProcesses.Values.ToList(); public ProcessMonitorManagerService( IProcessMonitorService processMonitorService, IProcessPowerPlanAssociationService associationService, IPowerPlanService powerPlanService, INotificationService notificationService, IApplicationSettingsService settingsService, IProcessService processService, ICoreMaskService coreMaskService, ILogger logger, IEnhancedLoggingService enhancedLogger) { _processMonitorService = processMonitorService ?? throw new ArgumentNullException(nameof(processMonitorService)); _associationService = associationService ?? throw new ArgumentNullException(nameof(associationService)); _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService)); _notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService)); _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); _processService = processService ?? throw new ArgumentNullException(nameof(processService)); _coreMaskService = coreMaskService ?? throw new ArgumentNullException(nameof(coreMaskService)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _enhancedLogger = enhancedLogger ?? throw new ArgumentNullException(nameof(enhancedLogger)); // Initialize delay timer (used for delayed power plan changes) _delayTimer = new System.Threading.Timer(DelayedPowerPlanChangeCallback, null, Timeout.Infinite, Timeout.Infinite); // Subscribe to events _processMonitorService.ProcessStarted += OnProcessStarted; _processMonitorService.ProcessStopped += OnProcessStopped; _processMonitorService.MonitoringStatusChanged += OnMonitoringStatusChanged; _associationService.ConfigurationChanged += OnConfigurationChanged; } public async Task StartAsync() { if (_disposed) throw new ObjectDisposedException(nameof(ProcessMonitorManagerService)); await _stateMutationSemaphore.WaitAsync(); try { if (_isRunning) { return; } _logger.LogInformation("Starting Process Monitor Manager Service"); await _enhancedLogger.LogSystemEventAsync(LogEventTypes.System.ServiceStarted, "Process Monitor Manager Service starting"); SetStatus(true, "Starting..."); // Load configuration await _associationService.LoadConfigurationAsync(); _configuration = _associationService.Configuration; _logger.LogInformation("Configuration loaded with {AssociationCount} associations", _configuration.Associations.Count); await _enhancedLogger.LogSystemEventAsync(LogEventTypes.System.ConfigurationLoaded, $"Process monitoring configuration loaded with {_configuration.Associations.Count} associations"); // Start process monitoring await _processMonitorService.StartMonitoringAsync(); _logger.LogInformation("Process monitoring started"); Interlocked.Exchange(ref _pendingPowerPlanReevaluation, 0); await _enhancedLogger.LogProcessMonitoringEventAsync(LogEventTypes.ProcessMonitoring.MonitoringStarted, "ProcessMonitorService", 0, "WMI-based process monitoring started"); _isRunning = true; SetStatus(true, "Running"); _logger.LogInformation("Process Monitor Manager Service started successfully"); await _enhancedLogger.LogSystemEventAsync(LogEventTypes.System.ServiceStarted, "Process Monitor Manager Service started successfully"); } catch (Exception ex) { _logger.LogError(ex, "Failed to start Process Monitor Manager Service"); await _enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.StartAsync", new Dictionary { ["ServiceName"] = "ProcessMonitorManagerService" }); _isRunning = false; SetStatus(false, "Failed to start", $"Error: {ex.Message}", ex); throw; } finally { _stateMutationSemaphore.Release(); } // Evaluate current processes after startup lock is released await EvaluateCurrentProcessesAsync(); } public async Task StopAsync() { await _stateMutationSemaphore.WaitAsync(); try { if (!_isRunning) { return; } SetStatus(false, "Stopping..."); // Mark as stopped early to prevent new event handling while shutting down _isRunning = false; Interlocked.Exchange(ref _pendingPowerPlanReevaluation, 0); // Stop process monitoring await _processMonitorService.StopMonitoringAsync(); // Clear running processes foreach (var processId in _runningAssociatedProcesses.Keys) { _coreMaskService.UnregisterMaskApplication(processId); _processService.UntrackProcess(processId); } _runningAssociatedProcesses.Clear(); // Restore default power plan if configured if (_configuration?.DefaultPowerPlanGuid != null) { await ForceDefaultPowerPlanAsync(); } SetStatus(false, "Stopped"); } catch (Exception ex) { SetStatus(false, "Error stopping", $"Error: {ex.Message}", ex); throw; } finally { _stateMutationSemaphore.Release(); } } public async Task EvaluateCurrentProcessesAsync() { if (!_isRunning || _configuration == null) return; try { var currentProcesses = await _processMonitorService.GetRunningProcessesAsync(); var associatedProcesses = new List(); var currentProcessIds = new HashSet(currentProcesses.Select(p => p.ProcessId)); // Remove stale tracked processes that are no longer running foreach (var trackedPid in _runningAssociatedProcesses.Keys) { if (!currentProcessIds.Contains(trackedPid) && _runningAssociatedProcesses.TryRemove(trackedPid, out _)) { _coreMaskService.UnregisterMaskApplication(trackedPid); _processService.UntrackProcess(trackedPid); } } // Find all currently running processes that have associations foreach (var process in currentProcesses) { var association = _configuration.FindMatchingAssociation(process); if (association != null) { associatedProcesses.Add(process); _runningAssociatedProcesses[process.ProcessId] = process; } } // Determine which power plan should be active await DeterminePowerPlanAsync(associatedProcesses); } catch (Exception ex) { SetStatus(_isRunning, "Error evaluating processes", $"Error: {ex.Message}", ex); } } public async Task ForceDefaultPowerPlanAsync() { if (_configuration?.DefaultPowerPlanGuid == null) return; try { await _powerPlanChangeSemaphore.WaitAsync(); var currentPowerPlan = await _powerPlanService.GetActivePowerPlan(); var success = await _powerPlanService.SetActivePowerPlanByGuidAsync( _configuration.DefaultPowerPlanGuid, _configuration.PreventDuplicatePowerPlanChanges); if (success) { var newPowerPlan = await _powerPlanService.GetPowerPlanByGuidAsync(_configuration.DefaultPowerPlanGuid); // Note: We don't have a specific process for this event, so we'll use a dummy one var dummyProcess = new ProcessModel { Name = "System", ProcessId = -1 }; var dummyAssociation = new ProcessPowerPlanAssociation("System", _configuration.DefaultPowerPlanGuid, _configuration.DefaultPowerPlanName); ProcessPowerPlanChanged?.Invoke(this, new ProcessPowerPlanChangeEventArgs( dummyProcess, dummyAssociation, currentPowerPlan, newPowerPlan, "DefaultRestored")); // Show notification for default power plan restoration await _notificationService.ShowPowerPlanChangeNotificationAsync( currentPowerPlan?.Name ?? "Unknown", newPowerPlan?.Name ?? _configuration.DefaultPowerPlanName, ""); } } catch (Exception ex) { SetStatus(_isRunning, "Error setting default power plan", $"Error: {ex.Message}", ex); } finally { _powerPlanChangeSemaphore.Release(); } } public async Task GetCurrentActivePowerPlanAsync() { return await _powerPlanService.GetActivePowerPlan(); } public async Task RefreshConfigurationAsync() { await _associationService.LoadConfigurationAsync(); _configuration = _associationService.Configuration; _processMonitorService.UpdateSettings(); if (_isRunning) { await EvaluateCurrentProcessesAsync(); } } private async void OnProcessStarted(object? sender, ProcessEventArgs e) { if (!_isRunning || _configuration == null) return; if (string.IsNullOrWhiteSpace(e.Process.Name) || e.Process.ProcessId <= 0) { return; } try { await _enhancedLogger.LogProcessMonitoringEventAsync(LogEventTypes.ProcessMonitoring.Started, e.Process.Name, e.Process.ProcessId, "Process started and detected by monitoring"); var association = _configuration.FindMatchingAssociation(e.Process); if (association != null) { _runningAssociatedProcesses[e.Process.ProcessId] = e.Process; await _enhancedLogger.LogProcessMonitoringEventAsync(LogEventTypes.ProcessMonitoring.AssociationTriggered, e.Process.Name, e.Process.ProcessId, $"Process matched association for power plan: {association.PowerPlanName}"); // Apply CPU affinity mask if configured await ApplyCoreMaskAndPriorityAsync(e.Process, association); // Schedule power plan change with delay if configured if (_configuration.PowerPlanChangeDelayMs > 0) { Interlocked.Exchange(ref _pendingPowerPlanReevaluation, 1); _delayTimer.Change(_configuration.PowerPlanChangeDelayMs, Timeout.Infinite); await _enhancedLogger.LogSystemEventAsync(LogEventTypes.System.ConfigurationLoaded, $"Power plan change scheduled with {_configuration.PowerPlanChangeDelayMs}ms delay for process {e.Process.Name}"); } else { await ChangePowerPlanForProcess(e.Process, association, "ProcessStarted"); } } } catch (Exception ex) { await _enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.OnProcessStarted", new Dictionary { ["ProcessName"] = e.Process.Name, ["ProcessId"] = e.Process.ProcessId }); SetStatus(_isRunning, "Error handling process start", $"Error: {ex.Message}", ex); } } private async void OnProcessStopped(object? sender, ProcessEventArgs e) { if (!_isRunning || _configuration == null) return; try { if (_runningAssociatedProcesses.TryRemove(e.Process.ProcessId, out _)) { _coreMaskService.UnregisterMaskApplication(e.Process.ProcessId); _processService.UntrackProcess(e.Process.ProcessId); // Check if there are any other associated processes still running var remainingProcesses = _runningAssociatedProcesses.Values.ToList(); await DeterminePowerPlanAsync(remainingProcesses); } } catch (Exception ex) { SetStatus(_isRunning, "Error handling process stop", $"Error: {ex.Message}", ex); } } private void OnMonitoringStatusChanged(object? sender, MonitoringStatusEventArgs e) { var details = e.StatusMessage ?? (e.IsMonitoring ? "Monitoring active" : "Monitoring inactive"); SetStatus(_isRunning, $"Monitor: {details}", e.StatusMessage, e.Error); } private void OnConfigurationChanged(object? sender, ConfigurationChangedEventArgs e) { _configuration = _associationService.Configuration; if (_isRunning) { Task.Run(async () => await EvaluateCurrentProcessesAsync()); } // Keep process monitor settings synchronized with configuration edits _processMonitorService.UpdateSettings(); } private async void DelayedPowerPlanChangeCallback(object? state) { if (!_isRunning) return; if (Interlocked.Exchange(ref _pendingPowerPlanReevaluation, 0) == 0) { return; } var runningProcesses = _runningAssociatedProcesses.Values.ToList(); await DeterminePowerPlanAsync(runningProcesses); } private async Task DeterminePowerPlanAsync(IList associatedProcesses) { if (_configuration == null) return; try { if (associatedProcesses.Any()) { // Find the highest priority association among running processes var associations = associatedProcesses .Select(p => _configuration.FindMatchingAssociation(p)) .Where(a => a != null) .OrderByDescending(a => a!.Priority) .ToList(); if (associations.Any()) { var topAssociation = associations.First()!; var matchingProcess = associatedProcesses.First(p => topAssociation.MatchesProcess(p)); await ChangePowerPlanForProcess(matchingProcess, topAssociation, "ProcessStarted"); } } else { // No associated processes running, revert to default if (!string.IsNullOrEmpty(_configuration.DefaultPowerPlanGuid)) { await ForceDefaultPowerPlanAsync(); } } } catch (Exception ex) { SetStatus(_isRunning, "Error determining power plan", $"Error: {ex.Message}", ex); } } private async Task ChangePowerPlanForProcess(ProcessModel process, ProcessPowerPlanAssociation association, string action) { try { await _powerPlanChangeSemaphore.WaitAsync(); var currentPowerPlan = await _powerPlanService.GetActivePowerPlan(); var success = await _powerPlanService.SetActivePowerPlanByGuidAsync( association.PowerPlanGuid, _configuration?.PreventDuplicatePowerPlanChanges ?? true); if (success) { var newPowerPlan = await _powerPlanService.GetPowerPlanByGuidAsync(association.PowerPlanGuid); ProcessPowerPlanChanged?.Invoke(this, new ProcessPowerPlanChangeEventArgs( process, association, currentPowerPlan, newPowerPlan, action)); // Show notification for power plan change await _notificationService.ShowPowerPlanChangeNotificationAsync( currentPowerPlan?.Name ?? "Unknown", newPowerPlan?.Name ?? association.PowerPlanName, process.Name); } } catch (Exception ex) { SetStatus(_isRunning, "Error changing power plan", $"Error: {ex.Message}", ex); } finally { _powerPlanChangeSemaphore.Release(); } } private void SetStatus(bool isRunning, string status, string? details = null, Exception? error = null) { lock (_lockObject) { _status = status; } ServiceStatusChanged?.Invoke(this, new ServiceStatusEventArgs(isRunning, status, details, error)); // Show error notification if there's an error if (error != null) { Task.Run(async () => { try { await _notificationService.ShowErrorNotificationAsync( "Process Monitor Error", details ?? status, error); } catch (Exception ex) { _logger.LogError(ex, "Failed to show error notification"); } }); } } public void UpdateSettings() { // Update the process monitor service with new settings _processMonitorService.UpdateSettings(); _logger.LogDebug("ProcessMonitorManagerService settings updated"); } /// /// Applies CPU affinity mask and process priority from association when a process starts /// Based on CPUSetSetter's ProgramRule.SetMask pattern /// private async Task ApplyCoreMaskAndPriorityAsync(ProcessModel process, ProcessPowerPlanAssociation association) { try { // Apply CPU affinity mask if configured if (!string.IsNullOrEmpty(association.CoreMaskId)) { var coreMask = _coreMaskService.AvailableMasks.FirstOrDefault(m => m.Id == association.CoreMaskId); if (coreMask != null) { try { var affinity = coreMask.ToProcessorAffinity(); if (affinity > 0) { await _processService.SetProcessorAffinity(process, affinity); _processService.TrackAppliedMask(process.ProcessId, coreMask.Id); _coreMaskService.RegisterMaskApplication(process.ProcessId, coreMask.Id); _logger.LogInformation( "Applied CPU mask '{MaskName}' (affinity: 0x{Affinity:X}) to process {ProcessName} (PID: {ProcessId})", coreMask.Name, affinity, process.Name, process.ProcessId); await _enhancedLogger.LogProcessMonitoringEventAsync( LogEventTypes.ProcessMonitoring.AssociationTriggered, process.Name, process.ProcessId, $"CPU mask '{coreMask.Name}' applied automatically from association"); } } catch (Exception ex) { var blockedReason = BuildAffinityOrPriorityBlockedMessage(ex, process.Name, "affinity"); if (!string.IsNullOrEmpty(blockedReason)) { await _notificationService.ShowNotificationAsync( "Affinity blocked", blockedReason, NotificationType.Warning); } _logger.LogWarning(ex, "Failed to apply CPU mask '{MaskName}' to process {ProcessName} (PID: {ProcessId})", coreMask.Name, process.Name, process.ProcessId); await _enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.ApplyCoreMaskAndPriorityAsync", new Dictionary { ["ProcessName"] = process.Name, ["ProcessId"] = process.ProcessId, ["MaskName"] = coreMask.Name }); } } else { _logger.LogWarning( "Core mask ID '{CoreMaskId}' not found for process {ProcessName}, skipping affinity application", association.CoreMaskId, process.Name); } } // Apply process priority if configured if (!string.IsNullOrEmpty(association.ProcessPriority)) { if (Enum.TryParse(association.ProcessPriority, out var priority)) { try { var currentPriority = process.Priority; if (!Enum.IsDefined(typeof(ProcessPriorityClass), currentPriority)) { try { await _processService.RefreshProcessInfo(process); currentPriority = process.Priority; } catch (Exception refreshEx) { _logger.LogDebug(refreshEx, "Could not refresh process priority before tracking for {ProcessName} (PID: {ProcessId})", process.Name, process.ProcessId); } } if (Enum.IsDefined(typeof(ProcessPriorityClass), currentPriority)) { _processService.TrackPriorityChange(process.ProcessId, currentPriority); } await _processService.SetProcessPriority(process, priority); _logger.LogInformation( "Applied priority '{Priority}' to process {ProcessName} (PID: {ProcessId})", priority, process.Name, process.ProcessId); await _enhancedLogger.LogProcessMonitoringEventAsync( LogEventTypes.ProcessMonitoring.AssociationTriggered, process.Name, process.ProcessId, $"Priority '{priority}' applied automatically from association"); } catch (Exception ex) { var blockedReason = BuildAffinityOrPriorityBlockedMessage(ex, process.Name, "priority"); if (!string.IsNullOrEmpty(blockedReason)) { await _notificationService.ShowNotificationAsync( "Priority blocked", blockedReason, NotificationType.Warning); } _logger.LogWarning(ex, "Failed to apply priority '{Priority}' to process {ProcessName} (PID: {ProcessId})", priority, process.Name, process.ProcessId); await _enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.ApplyCoreMaskAndPriorityAsync", new Dictionary { ["ProcessName"] = process.Name, ["ProcessId"] = process.ProcessId, ["Priority"] = priority.ToString() }); } } else { _logger.LogWarning( "Invalid priority value '{Priority}' for process {ProcessName}, skipping priority application", association.ProcessPriority, process.Name); } } } catch (Exception ex) { _logger.LogError(ex, "Error applying CPU mask and priority to process {ProcessName} (PID: {ProcessId})", process.Name, process.ProcessId); await _enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.ApplyCoreMaskAndPriorityAsync", new Dictionary { ["ProcessName"] = process.Name, ["ProcessId"] = process.ProcessId, ["AssociationId"] = association.Id }); } } private static string BuildAffinityOrPriorityBlockedMessage(Exception ex, string processName, string operation) { var message = ex.Message ?? string.Empty; var lowered = message.ToLowerInvariant(); if (lowered.Contains("access denied") || lowered.Contains("anti-cheat") || lowered.Contains("anti cheat") || lowered.Contains("protected") || lowered.Contains("insufficient privileges") || ex is UnauthorizedAccessException) { return $"{operation} change blocked by Anti-Cheat/System for '{processName}'."; } return string.Empty; } public void Dispose() { if (_disposed) return; StopAsync().Wait(5000); // Wait up to 5 seconds for clean shutdown _delayTimer?.Dispose(); _powerPlanChangeSemaphore?.Dispose(); _stateMutationSemaphore?.Dispose(); _processMonitorService?.Dispose(); _disposed = true; } } }