Files
ResourceUsageAPI/README.md
T

425 lines
14 KiB
Markdown

# Resource Monitor Service for Unraid VM
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.
## 🚀 Features
### 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
- **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
### 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
## 📡 API Endpoints
The service runs on `http://localhost:5000` by default and provides the following endpoints:
### 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
### 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
### 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
```
### Option 2: Windows Service (Production)
```powershell
# Run as Administrator
cd C:\Work\DEV\ResourceUsageAPI\publish
.\install-service.bat
```
### Option 3: Standalone Executable
```powershell
cd C:\Work\DEV\ResourceUsageAPI\publish
.\ResourceMonitorService.exe
```
## ⚙️ Configuration
Configuration is managed through `appsettings.json`:
```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"
}
}
```
### Game Detection Configuration
The service supports advanced game detection through two complementary approaches:
#### **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
#### **Root Folder Detection**
Configure custom game directories for standalone games and non-platform installations:
```json
"GameRootFolders": [
"C:\\Games",
"D:\\Games",
"E:\\Games"
]
```
**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
**Example Game Detection:**
```
C:\Games\Cyberpunk 2077\bin\x64\Cyberpunk2077.exe
→ Game Name: "Cyberpunk 2077"
→ Platform: "Standalone"
D:\Games\The Witcher 3\witcher3.exe
→ Game Name: "The Witcher 3"
→ Platform: "Standalone"
```
**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
## 📊 Example API Responses
### 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
}
}
```
### CPU Usage
```json
{
"usage": 15.5,
"coreUsages": [12.1, 18.3, 14.7, 16.2],
"temperature": 65.0,
"maxFrequency": 4400,
"currentFrequency": 3200,
"isThrottling": false
}
```
### VM Information
```json
{
"isVirtualMachine": true,
"hypervisorVendor": "VMware",
"uptime": "1.16:55:30",
"bootTime": "2025-08-05T09:34:04Z",
"machineName": "WIN11-VM",
"domain": "WORKGROUP"
}
```
### 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": ""
}
```
### 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
}
```
### 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
```powershell
# Get system health
$health = Invoke-RestMethod -Uri "http://localhost:5000/api/health"
Write-Host "System Status: $($health.status)"
# Get CPU usage
$cpu = Invoke-RestMethod -Uri "http://localhost:5000/api/cpu-usage"
Write-Host "CPU Usage: $($cpu.usage)%"
# 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)"
}
# 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