Update project files and configurations for improved structure and maintainability

This commit is contained in:
Phoenix
2025-08-07 16:53:10 +08:00
parent 3b3bdf3d46
commit 3f64ace8a7
11 changed files with 1062 additions and 837 deletions
+386 -108
View File
@@ -1,146 +1,424 @@
# Resource Monitor Service v2.0
# Resource Monitor Service for Unraid VM
A comprehensive Windows VM monitoring service designed specifically for Unraid virtual machines. This service provides real-time system monitoring, alerting, and remote management capabilities through a REST API.
A comprehensive system monitoring service specifically designed for Windows VMs running on Unraid servers. This service provides real-time monitoring of CPU, memory, GPU, disk, network, and system resources through a RESTful API.
## 🚀 New Features in v2.0
## 🚀 Features
### Enhanced Monitoring
- **Multi-core CPU monitoring** with per-core usage and frequency tracking
- **Advanced memory monitoring** including paged/non-paged memory
- **Enhanced GPU monitoring** with NVIDIA GPU support via NVML
- **Comprehensive disk monitoring** with I/O performance metrics
- **Network monitoring** with per-adapter statistics
- **Temperature monitoring** for CPU, GPU, and storage devices
- **Process monitoring** with detailed resource usage tracking
### Core Monitoring
- **CPU Monitoring**: Per-core usage, frequency, temperature, and throttling detection
- **Memory Monitoring**: RAM usage, available memory, committed memory, and paging
- **GPU Monitoring**: NVIDIA GPU usage, memory utilization, temperature, fan speed, and power consumption (via NVML)
- **Disk Monitoring**: I/O statistics, space usage, and performance counters
- **Network Monitoring**: Bandwidth usage, packet statistics, and interface data
- **Temperature Monitoring**: CPU and hard drive temperature sensors
### VM-Specific Features
- **Hypervisor detection** (VMware, Hyper-V, QEMU/KVM, etc.)
- **VM information** including boot time and uptime tracking
- **Virtual machine optimization** for better performance in virtualized environments
- **VM Detection**: Automatically detects virtualization environment
- **Hypervisor Identification**: Identifies VMware, VirtualBox, Hyper-V, KVM, etc.
- **Unraid Optimization**: Optimized for Unraid VM environments
- **Resource Alerting**: Configurable thresholds for resource usage alerts
### Game Detection & Management
- **Multi-platform game detection** (Steam, Epic Games, GOG, Origin, Ubisoft)
- **Fullscreen detection** for gaming sessions
- **Game performance monitoring** with memory and CPU usage
- **Enhanced process management** with graceful termination options
### Advanced Features
- **Game Detection**: Multi-platform game detection with fullscreen monitoring and configurable root folders
- **Process Management**: View top processes with CPU/memory percentages, terminate processes via API
- **Smart Alerting**: Duration-based alerting to prevent false positives
- **System Control**: Remote shutdown/restart capabilities
- **Health Monitoring**: Comprehensive health checks and uptime tracking
- **Real-time Metrics**: CPU usage calculation and memory percentage tracking for processes
### Intelligent Alerting System
- **Configurable thresholds** for CPU, memory, GPU, and temperature
- **Duration-based alerting** to prevent false positives
- **Alert history** and active alert management
- **Automatic alert resolution** when conditions improve
## 📡 API Endpoints
### Improved API
- **RESTful endpoints** with structured responses
- **Enhanced error handling** and logging
- **Configurable CORS** and API key authentication
- **Health check endpoints** for monitoring service status
- RAM Usage
- GPU Usage
- Currently Running Steam Games (if any)
The service runs on `http://localhost:5000` by default and provides the following endpoints:
- **Process Management**: Provides an API to kill processes by their process ID.
### System Information
- `GET /api/system-info` - Complete system information including VM details
- `GET /api/vm/info` - VM-specific information (hypervisor, uptime, etc.)
- `GET /api/health` - Service health status and monitoring capabilities
- `GET /api/metrics` - Service metrics and performance overview
- `GET /api/config` - Current configuration settings
## Directory Structure
### Resource Monitoring
- `GET /api/resource-usage` - Complete resource usage overview
- `GET /api/cpu-usage` - Detailed CPU metrics with per-core data
- `GET /api/memory-usage` - Memory utilization and statistics
- `GET /api/gpu-usage` - NVIDIA GPU usage, memory, temperature, fan speed, and power consumption
- `GET /api/disk-usage` - Disk I/O and space usage for all drives
- `GET /api/network-usage` - Network interface statistics
- `GET /api/top-processes?count=10` - Top processes by CPU/memory usage with percentage data
```
ResourceUsageAPI/
├── Worker.cs
├── Program.cs
├── Startup.cs
└── NvmlWrapper.cs
### Game Detection
- `GET /api/current-game` - Currently running game information
- `GET /api/all-games` - All detected games on the system
- `GET /api/fullscreen-status` - Check if any game is running fullscreen
### Alerting System
- `GET /api/alerts/active` - Currently active alerts
- `GET /api/alerts/history?count=100` - Alert history
- `POST /api/alerts/{alertId}/resolve` - Manually resolve an alert
- `GET /api/alerts/enabled` - Check if alerting is enabled
### System Control
- `POST /api/process/kill` - Terminate a process (requires process ID and optional force flag)
- `POST /api/system/shutdown` - Shutdown, restart, or cancel system operations
- `POST /api/service/stop` - Stop the monitoring service
**Process Management Details:**
- The `/api/top-processes` endpoint returns processes sorted by CPU usage
- Each process includes real-time CPU usage percentage and memory usage percentage
- CPU usage is calculated using time-based measurements between API calls
- Memory usage percentage is calculated relative to total system memory
- Process termination supports both graceful (`force: false`) and forced (`force: true`) termination
## 🛠️ Installation & Usage
### Option 1: Console Application (Development/Testing)
```powershell
cd C:\Work\DEV\ResourceUsageAPI
dotnet run --configuration Release
```
## Code Analysis
### Option 2: Windows Service (Production)
```powershell
# Run as Administrator
cd C:\Work\DEV\ResourceUsageAPI\publish
.\install-service.bat
```
### Worker.cs
### Option 3: Standalone Executable
```powershell
cd C:\Work\DEV\ResourceUsageAPI\publish
.\ResourceMonitorService.exe
```
This file contains the main logic for monitoring system resources and exposing APIs.
## ⚙️ Configuration
- **Dependencies**: Uses `System.Diagnostics`, `Microsoft.AspNetCore.Builder`, `Newtonsoft.Json` among others.
- **Methods**:
- `ExecuteAsync`: Sets up the ASP.NET Core web application, defines routes for resource usage and process management, and runs the server.
- `GetComputerInfo`: Retrieves basic system information.
- `GetCpuUsage`: Fetches CPU usage and lists top three processes by CPU usage if usage is over 80%.
- `GetRamUsage`: Calculates RAM usage percentage.
- `GetTotalPhysicalMemory`: Retrieves total physical memory size.
- `GetGpuUsage`: Uses NVIDIA Management Library (NVML) to fetch GPU usage, temperature, and fan speed.
- `GetCurrentlyRunningGame`: Detects if a Steam game is running by checking process paths.
- `GetCurrentTime`: Returns the current time.
Configuration is managed through `appsettings.json`:
### Program.cs
```json
{
"MonitoringSettings": {
"UpdateIntervalMs": 5000,
"EnableGpuMonitoring": true,
"EnableDiskMonitoring": true,
"EnableNetworkMonitoring": true,
"EnableTemperatureMonitoring": true,
"EnableProcessMonitoring": true,
"EnableGameDetection": true,
"EnableAlerts": true,
"GamePlatformPaths": [
"\\steamapps\\common\\",
"\\Epic Games\\",
"\\GOG Galaxy\\Games\\",
"\\Origin Games\\",
"\\Ubisoft Game Launcher\\games\\"
],
"GameRootFolders": [
"C:\\Games",
"D:\\Games",
"E:\\Games"
]
},
"AlertThresholds": {
"CpuUsageThreshold": 80.0,
"MemoryUsageThreshold": 85.0,
"GpuUsageThreshold": 90.0,
"DiskUsageThreshold": 90.0,
"TemperatureThreshold": 80.0,
"AlertDurationSeconds": 30
},
"ApiSettings": {
"RequireApiKey": false,
"AllowedOrigins": ["http://localhost:4200", "http://unraid:4200"],
"BasePath": "/api"
}
}
```
This file sets up the hosting environment for the application.
### Game Detection Configuration
- **Dependencies**: Uses `Microsoft.Extensions.DependencyInjection` and `Microsoft.Extensions.Hosting`.
- **Methods**:
- `Main`: Entry point of the application, builds and runs the host.
- `CreateHostBuilder`: Configures services and determines if the application should run as a Windows service based on command-line arguments or environment variables.
The service supports advanced game detection through two complementary approaches:
### Startup.cs
#### **Platform-Based Detection**
Automatically detects games installed through popular game platforms:
- **Steam**: Games in `\steamapps\common\` directories
- **Epic Games Store**: Games in `\Epic Games\` directories
- **GOG Galaxy**: Games in `\GOG Galaxy\Games\` directories
- **EA Origin**: Games in `\Origin Games\` directories
- **Ubisoft Connect**: Games in `\Ubisoft Game Launcher\games\` directories
This file is not used in the current implementation since all routing and configuration are done within `Worker.cs`.
#### **Root Folder Detection**
Configure custom game directories for standalone games and non-platform installations:
- **Dependencies**: Uses `Microsoft.AspNetCore.Builder` and `Microsoft.AspNetCore.Hosting`.
- **Methods**:
- `ConfigureServices`: Placeholder method for adding services.
- `Configure`: Placeholder method for configuring application HTTP requests pipeline.
```json
"GameRootFolders": [
"C:\\Games",
"D:\\Games",
"E:\\Games"
]
```
### NvmlWrapper.cs
**How Root Folder Detection Works:**
- **Priority**: Root folders are checked **before** platform paths
- **Smart Naming**: Extracts game names from directory structure
- **Flexible Structure**: Supports any folder organization under root directories
- **Fallback Logic**: Uses file version info or executable name when needed
This file provides a C# wrapper for the NVIDIA Management Library (NVML) functions.
**Example Game Detection:**
```
C:\Games\Cyberpunk 2077\bin\x64\Cyberpunk2077.exe
→ Game Name: "Cyberpunk 2077"
→ Platform: "Standalone"
- **Dependencies**: Uses `System` and `System.Runtime.InteropServices`.
- **Methods**:
- Importing NVML DLL functions to interact with GPU hardware.
- Structures like `NvmlUtilization` are defined for handling utilization rates returned by NVML.
D:\Games\The Witcher 3\witcher3.exe
→ Game Name: "The Witcher 3"
→ Platform: "Standalone"
```
## Usage
**Configuration Tips:**
- Add drives where you install standalone games
- Include network drives if you store games on NAS
- Use absolute paths (e.g., `C:\Games`, not `Games`)
- Root folders are checked in order, so prioritize most common locations first
1. **Build the Project**: Use your preferred .NET build tool (e.g., `dotnet build`) to compile the project.
2. **Run the Application**:
- To run as a console application, execute the compiled binary directly.
- To run as a Windows service, use the command-line argument `--windows-service` or set the environment variable `RUN_AS_SERVICE` to `"true"`.
## 📊 Example API Responses
## APIs
### Health Check
```json
{
"status": "Healthy",
"timestamp": "2025-08-07T02:30:00Z",
"uptime": "1.16:55:30",
"activeAlerts": 0,
"monitoringEnabled": {
"gpu": true,
"disk": true,
"network": true,
"temperature": true,
"processes": true,
"games": true,
"alerts": true
}
}
```
- **Get Resource Usage**:
- URL: `/api/resource-usage`
- Method: GET
- Description: Retrieves current system resource usage.
- **Kill Process**:
- URL: `/api/kill-process`
- Method: POST
- Body: JSON with the process ID (`{"id": "1234"}`)
- Description: Kills the specified process.
### CPU Usage
```json
{
"usage": 15.5,
"coreUsages": [12.1, 18.3, 14.7, 16.2],
"temperature": 65.0,
"maxFrequency": 4400,
"currentFrequency": 3200,
"isThrottling": false
}
```
## Important Notes
### VM Information
```json
{
"isVirtualMachine": true,
"hypervisorVendor": "VMware",
"uptime": "1.16:55:30",
"bootTime": "2025-08-05T09:34:04Z",
"machineName": "WIN11-VM",
"domain": "WORKGROUP"
}
```
- Ensure that the NVIDIA Management Library (NVML) is installed on the system for GPU monitoring to work.
- The application allows CORS from all origins, which should be configured securely in production environments.
- Error handling and logging are minimal; consider adding robust error handling and logging mechanisms for a production-ready solution.
### GPU Usage
```json
{
"usage": 45,
"memoryUsage": 60,
"temperature": 72,
"fanSpeed": 65,
"powerUsage": 185000,
"memoryTotal": 8589934592,
"memoryUsed": 5153960755,
"isAvailable": true,
"name": "NVIDIA GeForce RTX 4070",
"driverVersion": "551.76",
"error": ""
}
```
## Contributing
### Game Detection
```json
{
"gameName": "Cyberpunk 2077",
"executableName": "Cyberpunk2077.exe",
"fullPath": "C:\\Games\\Cyberpunk 2077\\bin\\x64\\Cyberpunk2077.exe",
"processId": 8432,
"memoryUsage": 4294967296,
"cpuTime": "00:15:42.1250000",
"startTime": "2025-08-07T14:30:15.123456+08:00",
"platform": "Standalone",
"isFullscreen": true,
"fps": 0
}
```
Feel free to contribute by opening issues or submitting pull requests. Make sure to follow the project's coding style and best practices.
### Top Processes
```json
{
"value": [
{
"id": 11820,
"name": "WmiPrvSE",
"cpuUsage": 2.7276263,
"memoryUsage": 83120128,
"memoryUsagePercentage": 0.12576005,
"processorTime": "00:26:30.2500000",
"startTime": "2025-08-05T09:38:38.9837995+08:00",
"executablePath": "C:\\WINDOWS\\system32\\wbem\\wmiprvse.exe",
"commandLine": "C:\\WINDOWS\\system32\\wbem\\wmiprvse.exe"
},
{
"id": 8376,
"name": "explorer",
"cpuUsage": 1.5750673,
"memoryUsage": 403636224,
"memoryUsagePercentage": 0.61069816,
"processorTime": "00:24:36.7968750",
"startTime": "2025-08-07T15:26:31.096813+08:00",
"executablePath": "C:\\WINDOWS\\Explorer.EXE",
"commandLine": "C:\\WINDOWS\\Explorer.EXE"
}
],
"count": 2
}
```
## 🔧 PowerShell Usage Examples
# devnote
dotnet run
git add .
git commit -m "Add steam running games"
git push origin master
dotnet publish -c Release -o ./publish
```powershell
# Get system health
$health = Invoke-RestMethod -Uri "http://localhost:5000/api/health"
Write-Host "System Status: $($health.status)"
# devtest
Invoke-WebRequest -Uri "http://localhost:5000/api/kill-process" -Method POST -Body "1234" -Headers @{ "X-API-KEY" = "b7f3e8a1-4c2d-4d9f-9a6e-2a1c5d7f8e9a" }
# Get CPU usage
$cpu = Invoke-RestMethod -Uri "http://localhost:5000/api/cpu-usage"
Write-Host "CPU Usage: $($cpu.usage)%"
Invoke-WebRequest -Uri "http://192.168.50.52:5000/api/resource-usage" -Method GET -Headers @{ "X-API-KEY" = "b7f3e8a1-4c2d-4d9f-9a6e-2a1c5d7f8e9a" }
# Get GPU usage
$gpu = Invoke-RestMethod -Uri "http://localhost:5000/api/gpu-usage"
if ($gpu.isAvailable) {
Write-Host "GPU: $($gpu.name)"
Write-Host "GPU Usage: $($gpu.usage)%"
Write-Host "GPU Memory: $([math]::Round($gpu.memoryUsed / 1GB, 2))GB / $([math]::Round($gpu.memoryTotal / 1GB, 2))GB ($($gpu.memoryUsage)%)"
Write-Host "GPU Temperature: $($gpu.temperature)°C"
} else {
Write-Host "GPU not available: $($gpu.error)"
}
Use 'shutdown', 'restart', or 'cancel'.
Invoke-WebRequest -Uri "http://192.168.50.52:5000/api/force-shutdown" `
-Method POST `
-Headers @{ "X-API-KEY" = "b7f3e8a1-4c2d-4d9f-9a6e-2a1c5d7f8e9a" } `
-Body '{"Action": "shutdown", "DelaySeconds": 120}' `
-ContentType "application/json"
# Get current game (enhanced with root folder detection)
$game = Invoke-RestMethod -Uri "http://localhost:5000/api/current-game"
if ($game) {
Write-Host "Currently playing: $($game.gameName)"
Write-Host "Platform: $($game.platform)"
Write-Host "Executable: $($game.executableName)"
if ($game.isFullscreen) {
Write-Host "Running in fullscreen mode"
}
} else {
Write-Host "No game currently detected"
}
# Get all detected games
$allGames = Invoke-RestMethod -Uri "http://localhost:5000/api/all-games"
Write-Host "Detected games on system:"
foreach ($gameItem in $allGames) {
Write-Host " $($gameItem.gameName) ($($gameItem.platform)) - Memory: $([math]::Round($gameItem.memoryUsage / 1MB, 0))MB"
}
# Get top processes by CPU usage
$processes = Invoke-RestMethod -Uri "http://localhost:5000/api/top-processes?count=5"
Write-Host "Top 5 processes by CPU usage:"
foreach ($proc in $processes.value) {
Write-Host " $($proc.name): $($proc.cpuUsage.ToString('F2'))% CPU, $($proc.memoryUsagePercentage.ToString('F2'))% Memory"
}
# Terminate a process (example - be careful!)
$killRequest = @{
ProcessId = 1234
Force = $false
} | ConvertTo-Json
# Invoke-RestMethod -Uri "http://localhost:5000/api/process/kill" -Method Post -Body $killRequest -ContentType "application/json"
# Shutdown system with 60-second delay
$shutdownRequest = @{
Action = "shutdown"
DelaySeconds = 60
Message = "Scheduled maintenance shutdown"
} | ConvertTo-Json
Invoke-RestMethod -Uri "http://localhost:5000/api/system/shutdown" -Method Post -Body $shutdownRequest -ContentType "application/json"
```
## 🚨 Known Warnings (Non-Critical)
The service may show warnings in VM environments that don't affect functionality:
- **Performance Counter Warnings**: Some performance counters may not be available in VMs
- **Temperature Sensor Access**: Some temperature sensors require elevated privileges
- **Process Access Denied**: Some system processes require elevated privileges to access
- **Windows.Forms Compatibility**: Game detection works despite .NET Framework compatibility warnings
These warnings are expected in VM environments and the service continues to function normally.
## 🎯 Perfect for Unraid
This service is specifically optimized for Windows VMs running on Unraid:
- **VM Detection**: Automatically detects and reports virtualization status
- **Resource Monitoring**: Tracks VM resource allocation and usage
- **Gaming Support**: Detects games and monitors performance impact
- **Remote Management**: Full API control for integration with Unraid dashboard
- **Alert System**: Configurable alerts for resource thresholds
- **Health Monitoring**: Comprehensive health checks for VM status
## 📝 Logging
The service uses Serilog for structured logging:
- Console output for real-time monitoring
- File logging for persistent records
- Configurable log levels (Debug, Information, Warning, Error)
- Smart error suppression to prevent log spam in VM environments
## 🔐 Security
- Optional API key authentication
- CORS support for web dashboard integration
- Process termination requires explicit API calls
- System shutdown/restart requires explicit API calls
- Configurable allowed origins for API access
## 📈 Performance
- Lightweight background monitoring (5-second intervals by default)
- Efficient memory usage with smart caching and cleanup of old process data
- Non-blocking async operations
- Real-time CPU usage calculation for individual processes
- Graceful error handling for VM-specific limitations
- Configurable monitoring intervals and features
- Smart process tracking with automatic cleanup to prevent memory leaks
## 🆘 Support
For issues or questions:
1. Check the console output for warnings/errors
2. Review the configuration in `appsettings.json`
3. Test individual API endpoints using PowerShell or curl
4. Check Windows Event Logs if running as a service
---
**Version**: 2.1.0
**Target Framework**: .NET 9.0
**Platforms**: Windows (VM optimized)
**License**: Open Source
### Recent Updates
- **v2.1.0**: Added configurable game root folders for enhanced standalone game detection
- **v2.0.0**: Initial release with comprehensive system monitoring and game detection