Add start-service.bat script for Resource Monitor Service v2.0

- Introduced a batch script to simplify the startup process for the Resource Monitor Service.
- Included checks for .NET 9.0 Runtime installation.
- Added build and run commands for the service with appropriate error handling.
- Provided user instructions and API documentation links in the script output.
This commit is contained in:
Phoenix
2025-08-07 02:39:54 +08:00
parent 294438145a
commit 823e467078
17 changed files with 10419 additions and 363 deletions
+248
View File
@@ -0,0 +1,248 @@
# 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, temperature (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
- **Process Management**: View top processes, 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
## 📡 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` - GPU usage, memory, and temperature
- `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
### 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
## 🛠️ 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
},
"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"
}
}
```
## 📊 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"
}
```
## 🔧 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 current game
$game = Invoke-RestMethod -Uri "http://localhost:5000/api/current-game"
if ($game.isGameRunning) {
Write-Host "Currently playing: $($game.gameName)"
}
# 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
- Non-blocking async operations
- Graceful error handling for VM-specific limitations
- Configurable monitoring intervals and features
## 🆘 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.0.0
**Target Framework**: .NET 9.0
**Platforms**: Windows (VM optimized)
**License**: Open Source