Compare commits
7 Commits
156ae148a7
...
shutdown
| Author | SHA1 | Date | |
|---|---|---|---|
| 4cc0e99149 | |||
| a42c5753c9 | |||
| 78076a984b | |||
| 77f6c5abe1 | |||
| 5eec358b68 | |||
| 7c1cbb44f8 | |||
| 06ea991a6c |
@@ -1,7 +1,111 @@
|
||||
# dotnet
|
||||
# Resource Usage API
|
||||
|
||||
dotnet run
|
||||
git add .
|
||||
git commit -m "Add steam running games"
|
||||
git push origin master
|
||||
dotnet publish -c Release -o ./publish
|
||||
This project is a background service developed using ASP.NET Core that monitors system resource usage, such as CPU, RAM, GPU, and running games. The service provides APIs to fetch the current resource usage and kill specified processes.
|
||||
|
||||
## Features
|
||||
|
||||
- **Resource Monitoring**: Fetches detailed information about the system's resources, including:
|
||||
- Current Time
|
||||
- Computer Information (Machine Name, OS Version, Architecture, Processor Count)
|
||||
- CPU Usage
|
||||
- RAM Usage
|
||||
- GPU Usage
|
||||
- Currently Running Steam Games (if any)
|
||||
|
||||
- **Process Management**: Provides an API to kill processes by their process ID.
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
ResourceUsageAPI/
|
||||
├── Worker.cs
|
||||
├── Program.cs
|
||||
├── Startup.cs
|
||||
└── NvmlWrapper.cs
|
||||
```
|
||||
|
||||
## Code Analysis
|
||||
|
||||
### Worker.cs
|
||||
|
||||
This file contains the main logic for monitoring system resources and exposing APIs.
|
||||
|
||||
- **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.
|
||||
|
||||
### Program.cs
|
||||
|
||||
This file sets up the hosting environment for the application.
|
||||
|
||||
- **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.
|
||||
|
||||
### Startup.cs
|
||||
|
||||
This file is not used in the current implementation since all routing and configuration are done within `Worker.cs`.
|
||||
|
||||
- **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.
|
||||
|
||||
### NvmlWrapper.cs
|
||||
|
||||
This file provides a C# wrapper for the NVIDIA Management Library (NVML) functions.
|
||||
|
||||
- **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.
|
||||
|
||||
## Usage
|
||||
|
||||
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"`.
|
||||
|
||||
## APIs
|
||||
|
||||
- **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.
|
||||
|
||||
## Important Notes
|
||||
|
||||
- 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.
|
||||
|
||||
## Contributing
|
||||
|
||||
Feel free to contribute by opening issues or submitting pull requests. Make sure to follow the project's coding style and best practices.
|
||||
|
||||
|
||||
## devnote
|
||||
- **Commonlly use command**:
|
||||
- dotnet run
|
||||
- git add .
|
||||
- git commit -m "Add steam running games"
|
||||
- git push origin master
|
||||
- dotnet publish -c Release -o ./publish
|
||||
|
||||
- **Using git bash**:
|
||||
- curl -X POST "http://localhost:5000/api/kill-process" -H "Content-Type: application/json" -d '3333333'
|
||||
@@ -22,6 +22,16 @@ namespace ResourceMonitorService
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder();
|
||||
/* builder.WebHost.ConfigureKestrel(options =>
|
||||
{
|
||||
options.ListenAnyIP(5000); // Replace 5000 with your desired port
|
||||
}); */
|
||||
/* builder.WebHost.ConfigureKestrel(options =>
|
||||
{
|
||||
var url = builder.Configuration.GetValue<string>("Kestrel:Endpoints:Http:Url");
|
||||
var port = url.Split(':').Last();
|
||||
options.ListenAnyIP(int.Parse(port));
|
||||
}); */
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("AllowAllOrigins",
|
||||
@@ -59,7 +69,42 @@ namespace ResourceMonitorService
|
||||
await context.Response.WriteAsync(json);
|
||||
});
|
||||
|
||||
_ = app.RunAsync(stoppingToken);
|
||||
app.MapPost("/api/kill-process", async context =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var idStr = await new StreamReader(context.Request.Body).ReadToEndAsync();
|
||||
int processId = Convert.ToInt32(idStr);
|
||||
|
||||
Process[] processes = Process.GetProcesses().Where(p => p.Id == processId).ToArray();
|
||||
|
||||
if (processes.Length > 0)
|
||||
{
|
||||
foreach (var process in processes)
|
||||
{
|
||||
try
|
||||
{
|
||||
process.Kill();
|
||||
await context.Response.WriteAsync($"Process with ID {processId} has been killed.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await context.Response.WriteAsync($"Error killing process with ID {processId}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
await context.Response.WriteAsync($"No process found with ID {processId}.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await context.Response.WriteAsync($"An error occurred: {ex.Message}");
|
||||
}
|
||||
});
|
||||
|
||||
app.RunAsync(stoppingToken);
|
||||
|
||||
await Task.Delay(Timeout.Infinite, stoppingToken);
|
||||
}
|
||||
@@ -77,17 +122,11 @@ namespace ResourceMonitorService
|
||||
|
||||
private object GetCpuUsage()
|
||||
{
|
||||
#pragma warning disable CA1416 // Validate platform compatibility
|
||||
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
|
||||
#pragma warning restore CA1416 // Validate platform compatibility
|
||||
#pragma warning disable CA1416 // Validate platform compatibility
|
||||
cpuCounter.NextValue();
|
||||
#pragma warning restore CA1416 // Validate platform compatibility
|
||||
Thread.Sleep(1000); // Wait a second to get a valid reading
|
||||
|
||||
#pragma warning disable CA1416 // Validate platform compatibility
|
||||
var usage = cpuCounter.NextValue();
|
||||
#pragma warning restore CA1416 // Validate platform compatibility
|
||||
if (usage > 80)
|
||||
{
|
||||
// Get the current processes and sort them by CPU usage in descending order
|
||||
@@ -99,18 +138,21 @@ namespace ResourceMonitorService
|
||||
Usage = usage,
|
||||
Process1 = new
|
||||
{
|
||||
Id = processes.ElementAt(0).Id,
|
||||
Name = processes.ElementAt(0).ProcessName,
|
||||
TotalProcessorTime = processes.ElementAt(0).TotalProcessorTime,
|
||||
WorkingSet64 = processes.ElementAt(0).WorkingSet64 / (1024 * 1024) // Convert to MB
|
||||
},
|
||||
Process2 = new
|
||||
{
|
||||
Id = processes.ElementAt(1).Id,
|
||||
Name = processes.ElementAt(1).ProcessName,
|
||||
TotalProcessorTime = processes.ElementAt(1).TotalProcessorTime,
|
||||
WorkingSet64 = processes.ElementAt(1).WorkingSet64 / (1024 * 1024) // Convert to MB
|
||||
},
|
||||
Process3 = new
|
||||
{
|
||||
Id = processes.ElementAt(2).Id,
|
||||
Name = processes.ElementAt(2).ProcessName,
|
||||
TotalProcessorTime = processes.ElementAt(2).TotalProcessorTime,
|
||||
WorkingSet64 = processes.ElementAt(2).WorkingSet64 / (1024 * 1024) // Convert to MB
|
||||
@@ -126,30 +168,20 @@ namespace ResourceMonitorService
|
||||
|
||||
private float GetRamUsage()
|
||||
{
|
||||
#pragma warning disable CA1416 // Validate platform compatibility
|
||||
var ramCounter = new PerformanceCounter("Memory", "Available MBytes");
|
||||
#pragma warning restore CA1416 // Validate platform compatibility
|
||||
var totalMemory = GetTotalPhysicalMemory();
|
||||
#pragma warning disable CA1416 // Validate platform compatibility
|
||||
var availableMemory = ramCounter.NextValue() * 1024 * 1024;
|
||||
#pragma warning restore CA1416 // Validate platform compatibility
|
||||
return (float)(totalMemory - availableMemory) / totalMemory * 100;
|
||||
}
|
||||
|
||||
private ulong GetTotalPhysicalMemory()
|
||||
{
|
||||
ulong totalMemory = 0;
|
||||
#pragma warning disable CA1416 // Validate platform compatibility
|
||||
var searcher = new ManagementObjectSearcher("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem");
|
||||
#pragma warning restore CA1416 // Validate platform compatibility
|
||||
#pragma warning disable CA1416 // Validate platform compatibility
|
||||
foreach (var obj in searcher.Get())
|
||||
{
|
||||
#pragma warning disable CA1416 // Validate platform compatibility
|
||||
totalMemory = (ulong)obj["TotalPhysicalMemory"];
|
||||
#pragma warning restore CA1416 // Validate platform compatibility
|
||||
}
|
||||
#pragma warning restore CA1416 // Validate platform compatibility
|
||||
return totalMemory;
|
||||
}
|
||||
|
||||
@@ -185,9 +217,7 @@ namespace ResourceMonitorService
|
||||
{
|
||||
try
|
||||
{
|
||||
#pragma warning disable CS8602 // Dereference of a possibly null reference.
|
||||
var filePath = process.MainModule.FileName;
|
||||
#pragma warning restore CS8602 // Dereference of a possibly null reference.
|
||||
if (filePath.Contains(@"\steamapps\common\"))
|
||||
{
|
||||
// Extract the game directory name
|
||||
|
||||
@@ -4,5 +4,13 @@
|
||||
"Default": "Information",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
},
|
||||
"RunAsWindowsService": false,
|
||||
"Kestrel": {
|
||||
"Endpoints": {
|
||||
"Http": {
|
||||
"Url": "http://*:5000"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user