Files
ResourceUsageAPI/README.md
T

559 lines
19 KiB
Markdown

# Resource Monitor Service
A comprehensive system monitoring service with a modern web dashboard for real-time resource monitoring. Originally designed for Windows VMs running on Unraid servers, now featuring a responsive web interface for easy monitoring and management.
## 🌟 New: Web Dashboard
Access the interactive web dashboard at `http://localhost:5000` featuring:
- **Real-time Monitoring**: Live updates every 15 seconds via SignalR
- **Responsive Design**: Mobile-friendly interface built with Tailwind CSS
- **Interactive Controls**: Toggle auto-refresh, show/hide sections, manual refresh
- **Game Detection**: Prominent game monitoring with process termination
- **Process Management**: View and terminate top processes
- **System Details**: Comprehensive system information and disk usage
- **Performance Charts**: Historical CPU and memory usage graphs
- **API Documentation**: Built-in Swagger/OpenAPI interface at `/swagger`
## 🚀 Features
### Web Dashboard
- **Modern Interface**: Clean, responsive design with dark/light themes
- **Real-time Updates**: SignalR-powered live data updates
- **Auto-refresh Control**: Toggle between automatic and manual refresh modes
- **Game Detection Section**: Monitor running games with termination capability
- **Process Management**: View top processes with one-click termination
- **System Information**: Detailed hardware and software information
- **Disk Usage Visualization**: Visual disk space utilization
- **Performance Charts**: Historical data visualization with Chart.js
- **Mobile Responsive**: Works seamlessly on phones, tablets, and desktop
### 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
- **Telegram Bot Integration**: Real-time alerts via Telegram bot with customizable notifications
- **System Control**: Remote shutdown/restart capabilities with timer support (hidden feature)
### 🔐 Hidden System Control Feature
For security reasons, the system control feature is hidden by default. To access it:
**Activation Methods:**
1. **Triple-click** on the "Resource Monitor" title in the navigation bar
2. **Keyboard shortcut**: `Ctrl + Shift + P`
**Features:**
- **Shutdown**: Graceful or forced system shutdown
- **Restart**: System restart with optional force
- **Timer Support**: Delay execution from 0 to 86400 seconds (24 hours)
- **Safety Confirmations**: Multiple confirmation dialogs before execution
**Usage:**
1. Activate the system control button using one of the methods above
2. Click the red "System" button that appears in the navigation
3. Set optional timer (leave empty for immediate action)
4. Choose shutdown or restart
5. Confirm the action
⚠️ **Warning**: Use this feature with extreme caution as it will shut down or restart the entire system.
- **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 a web server on `http://localhost:5000` providing:
### Web Interface
- `GET /` - **Main Dashboard** - Interactive web interface for monitoring
- `GET /swagger` - **API Documentation** - Interactive API explorer and documentation
### REST API
All API endpoints are available at `http://localhost:5000/api/[endpoint]`:
### System Information
- `GET /api/resource/usage` - **Complete resource overview** - All monitoring data in one call
- `GET /api/resource/system-info` - Complete system information including VM details
- `GET /api/resource/cpu` - Detailed CPU metrics with per-core data
- `GET /api/resource/memory` - Memory utilization and statistics
- `GET /api/resource/gpu` - NVIDIA GPU usage, memory, temperature, fan speed, and power consumption
- `GET /api/resource/disks` - Disk I/O and space usage for all drives
- `GET /api/resource/network` - Network interface statistics
- `GET /api/resource/processes?count=10` - Top processes by CPU/memory usage with percentage data
### Process Management
- `POST /api/resource/kill-process/{processId}` - **Terminate Process** - End any process by ID
### Real-time Updates
- **SignalR Hub**: `/resourceHub` - Real-time data updates every 15 seconds
### 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
### Telegram Bot Integration
- `GET /api/telegram/status` - Check Telegram bot status and connection
- `POST /api/telegram/test` - Send a test alert to verify bot configuration
### 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: Web Dashboard (Recommended)
```powershell
cd C:\Work\DEV\ResourceUsageAPI
dotnet run --configuration Release
```
Then open your browser to `http://localhost:5000` for the interactive dashboard.
### Option 2: Windows Service (Production)
```powershell
# Run as Administrator
cd C:\Work\DEV\ResourceUsageAPI
.\install-service.ps1
```
### Option 3: Linux Service (if running on Linux)
```bash
cd /path/to/ResourceUsageAPI
chmod +x install-service.sh
sudo ./install-service.sh
```
### Option 4: Standalone Executable
```powershell
cd C:\Work\DEV\ResourceUsageAPI
dotnet build --configuration Release
dotnet publish --configuration Release
cd bin\Release\net9.0-windows\publish
.\ResourceMonitorService.exe
```
## 🎮 Web Dashboard Features
### Dashboard Overview
- **Resource Cards**: CPU, Memory, GPU, and Network usage with visual progress bars
- **Game Detection**: Prominent section showing currently running games
- **Auto-refresh Toggle**: Control automatic updates (15-second intervals)
- **Manual Refresh**: Force immediate data updates
- **Responsive Design**: Works on desktop, tablet, and mobile devices
### Interactive Sections
- **Processes**: View and terminate top CPU/memory consuming processes
- **Details**: System information, disk usage, and performance charts
- **Game Management**: Monitor and terminate running games
- **Real-time Charts**: Historical CPU and memory usage visualization
### Controls
- **Auto: ON/OFF** - Toggle automatic data updates
- **Processes** - Show/hide process management table
- **Details** - Show/hide system information and charts
- **Refresh** - Manually update all data immediately
## 📊 Service Management
### Starting and Stopping the Service
```powershell
# Start the service
Start-Service "ResourceMonitorService"
# Stop the service
Stop-Service "ResourceMonitorService"
# Get service status
Get-Service "ResourceMonitorService"
# Restart the service
Restart-Service "ResourceMonitorService"
```
### Development Mode
For development and testing:
```powershell
# Run in development mode with hot reload
dotnet run --environment Development
# Access the dashboard at http://localhost:5000
# Access Swagger API documentation at http://localhost:5000/swagger
```
### Troubleshooting
- **Service won't start**: Check the logs in the `logs/` directory
- **No GPU data**: Make sure you have an NVIDIA GPU and drivers installed
- **High CPU usage**: Adjust monitoring intervals in `appsettings.json`
- **Web dashboard not accessible**: Verify firewall settings and ensure port 5000 is available
- **Game detection issues**: Check if games are running from standard installation directories
- **API errors**: Verify endpoints using Swagger documentation at `/swagger`
- **Performance issues**: Consider increasing `UpdateIntervalMs` in configuration
## ⚙️ Configuration
Configuration is managed through `appsettings.json`:
```json
{
"MonitoringSettings": {
"UpdateIntervalMs": 15000,
"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"
]
},
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5000"
},
"Https": {
"Url": "https://localhost:5001"
}
}
}
}
```
### 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
### Telegram Bot Alerts
The service supports real-time alert notifications via Telegram bot. To set up Telegram alerts:
1. **Create a Telegram Bot** - Contact `@BotFather` on Telegram and create a new bot
2. **Get Chat ID** - Send a message to your bot, then visit `https://api.telegram.org/bot<TOKEN>/getUpdates`
3. **Configure Settings** - Add Telegram configuration to your `appsettings.json`:
```json
{
"MonitoringSettings": {
"Telegram": {
"IsEnabled": true,
"BotToken": "123456789:ABCdefGHIjklMNOpqrSTUvwxyz",
"ChatIds": [123456789, -987654321],
"SendWarningAlerts": true,
"SendCriticalAlerts": true,
"SendResolutionNotifications": true,
"MessageTemplate": "🚨 *{Level} Alert*\n\n📊 *{Component}*\n💬 {Message}\n⏰ {Timestamp}",
"ResolutionTemplate": "✅ *Alert Resolved*\n\n📊 *{Component}*\n💬 {Message}\n⏰ Resolved at {ResolvedAt}"
}
}
}
```
**Features:**
- **Multiple Chats**: Send alerts to multiple users/groups by adding chat IDs
- **Customizable Templates**: Modify message format with placeholders for alert data
- **Alert Filtering**: Choose which alert levels to send (Warning/Critical)
- **Silent Notifications**: Warning alerts are sent silently, critical alerts with sound
- **Resolution Notifications**: Optional notifications when alerts are resolved
📋 For detailed setup instructions, see [TELEGRAM_SETUP.md](TELEGRAM_SETUP.md)
## 📊 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
# Access the web dashboard
Start-Process "http://localhost:5000"
# Get complete resource overview
$resources = Invoke-RestMethod -Uri "http://localhost:5000/api/resource/usage"
Write-Host "CPU: $($resources.cpu.usage.ToString('F1'))%"
Write-Host "Memory: $($resources.memory.usagePercentage.ToString('F1'))%"
Write-Host "GPU: $($resources.gpu.usage)%"
# Get system information
$systemInfo = Invoke-RestMethod -Uri "http://localhost:5000/api/resource/system-info"
Write-Host "Machine: $($systemInfo.machineName)"
Write-Host "OS: $($systemInfo.osVersion)"
Write-Host "CPU: $($systemInfo.cpuName)"
# Get disk usage
$disks = Invoke-RestMethod -Uri "http://localhost:5000/api/resource/disks"
foreach ($disk in $disks) {
$freeGB = [math]::Round($disk.freeSpace / 1GB, 1)
$totalGB = [math]::Round($disk.totalSize / 1GB, 1)
Write-Host "$($disk.driveLetter): $freeGB GB free of $totalGB GB"
}
# Get top processes
$processes = Invoke-RestMethod -Uri "http://localhost:5000/api/resource/processes?count=5"
Write-Host "Top 5 processes by CPU usage:"
foreach ($proc in $processes) {
if ($proc.cpuUsage) {
Write-Host " $($proc.name): $($proc.cpuUsage.ToString('F1'))% CPU"
}
}
# Terminate a process (example - be careful!)
# Invoke-RestMethod -Uri "http://localhost:5000/api/resource/kill-process/1234" -Method Post
```
## 🚨 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 (15-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