Compare commits

..

4 Commits

29 changed files with 79 additions and 547 deletions
@@ -0,0 +1,7 @@
namespace MonitorAgent.API.Contracts;
public class ConnectionsCountResponse
{
public int Tcp {get;set;}
public int Udp {get;set;}
}
@@ -48,4 +48,17 @@ public class MonitorController(
return Ok(response); return Ok(response);
} }
[HttpGet("connectionsCount")]
public async Task<ActionResult> GetConnectionsCountAsync(CancellationToken cancellationToken = default)
{
var count = await monitorService.GetConnectionsCountAsync(cancellationToken);
var response = new ConnectionsCountResponse
{
Tcp = count.TcpCount,
Udp = count.UdpCount
};
return Ok(response);
}
} }
@@ -15,7 +15,9 @@ builder.Services.AddSwaggerGen();
builder.Services.Configure<CpuMonitorSettings>(builder.Configuration.GetSection("CpuMonitorSettings")); builder.Services.Configure<CpuMonitorSettings>(builder.Configuration.GetSection("CpuMonitorSettings"));
builder.Services.AddScoped<IProcessStarterService, ProcessStarterService>();
builder.Services.AddScoped<IMonitorService, MonitorService>(); builder.Services.AddScoped<IMonitorService, MonitorService>();
builder.Services.AddSingleton<RawCpuMonitorService>(); builder.Services.AddSingleton<RawCpuMonitorService>();
builder.Services.AddSingleton<CpuMonitorBackgroundService>(); builder.Services.AddSingleton<CpuMonitorBackgroundService>();
builder.Services.AddHostedService(provider => provider.GetRequiredService<CpuMonitorBackgroundService>()); builder.Services.AddHostedService(provider => provider.GetRequiredService<CpuMonitorBackgroundService>());
@@ -30,7 +30,7 @@ public class MonitorService : IMonitorService
public async Task<decimal> GetUptimeAsync(CancellationToken cancellationToken = default) public async Task<decimal> GetUptimeAsync(CancellationToken cancellationToken = default)
{ {
var uptime = await File.ReadAllTextAsync("/proc/uptime", cancellationToken); var uptime = await File.ReadAllTextAsync("/proc/uptime", cancellationToken);
return decimal.Parse(uptime.Split()[1], CultureInfo.InvariantCulture); return decimal.Parse(uptime.Split()[0], CultureInfo.InvariantCulture);
} }
public async Task<MemoryInfo> GetMemoryInfoAsync(CancellationToken cancellationToken = default) public async Task<MemoryInfo> GetMemoryInfoAsync(CancellationToken cancellationToken = default)
@@ -74,5 +74,16 @@ public class MonitorService : IMonitorService
return loadavg; return loadavg;
} }
// TODO: проверить на других системах
public async Task<ConnectionsCount> GetConnectionsCountAsync(CancellationToken cancellationToken = default)
{
var sockstat = await File.ReadAllLinesAsync("/proc/net/sockstat", cancellationToken);
return new ConnectionsCount(
int.Parse(sockstat[0].Split()[2]),
int.Parse(sockstat[1].Split()[2])
);
}
public static int ParseInt(string str) => int.Parse(Regex.Match(str, @"\d+").Value); public static int ParseInt(string str) => int.Parse(Regex.Match(str, @"\d+").Value);
} }
@@ -0,0 +1,27 @@
using MonitorAgent.Core.Abstraction;
using System.Diagnostics;
namespace MonitorAgent.Application.Services;
public class ProcessStarterService : IProcessStarterService
{
public async Task<string> StartProcessAsync(
string fileName, string arguments, CancellationToken cancellationToken = default)
{
using var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
process.Start();
return await process.StandardOutput.ReadToEndAsync(cancellationToken);
}
}
@@ -4,9 +4,11 @@ namespace MonitorAgent.Core.Abstraction;
public interface IMonitorService public interface IMonitorService
{ {
public Task<decimal> GetUptimeAsync(CancellationToken cancellationToken = default); public Task<decimal> GetUptimeAsync(CancellationToken cancellationToken);
public Task<MemoryInfo> GetMemoryInfoAsync(CancellationToken cancellationToken = default); public Task<MemoryInfo> GetMemoryInfoAsync(CancellationToken cancellationToken);
public Task<decimal[]> GetLoadAverageAsync(CancellationToken cancellationToken = default); public Task<decimal[]> GetLoadAverageAsync(CancellationToken cancellationToken);
public Task<ConnectionsCount> GetConnectionsCountAsync(CancellationToken cancellationToken);
} }
@@ -0,0 +1,6 @@
namespace MonitorAgent.Core.Abstraction;
public interface IProcessStarterService
{
Task<string> StartProcessAsync(string fileName, string arguments, CancellationToken cancellationToken);
}
@@ -0,0 +1,7 @@
namespace MonitorAgent.Core.Models;
public class ConnectionsCount(int tcp, int udp)
{
public readonly int TcpCount = tcp;
public readonly int UdpCount = udp;
}
@@ -1,67 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using MonitorPanel.Core.Abstractions;
using MonitorPanel.Core.Models;
using MonitorPanel.API.Dto;
namespace MonitorPanel.API.Controllers;
[ApiController]
[Route("[controller]")]
public class ServerController(IServerService serverService) : ControllerBase
{
[HttpGet("all")]
public async Task<ActionResult<List<ServerDto>>> GetAllServers(CancellationToken cancellationToken = default)
{
var servers = await serverService.GetAllServersAsync(cancellationToken);
return Ok(servers.Select(s => new ServerDto
{
Id = s.Id,
Name = s.Name,
Address = s.Address,
Path = s.Path,
IsHttps = s.IsHttps,
Port = s.Port
}));
}
[HttpGet("{id}")]
public async Task<ActionResult<ServerDto>> GetServerById(Guid id, CancellationToken cancellationToken = default)
{
var server = await serverService.GetServerByIdAsync(id, cancellationToken);
if (server == null)
{
return NotFound();
}
return Ok(new ServerDto
{
Id = server.Id,
Name = server.Name,
Address = server.Address,
Path = server.Path,
IsHttps = server.IsHttps,
Port = server.Port
});
}
[HttpPost]
public async Task<IActionResult> AddServer(ServerDto dto, CancellationToken cancellationToken = default)
{
var server = new Server(Guid.NewGuid(), dto.Name, dto.Address, dto.Path, dto.IsHttps, dto.Port);
var id = await serverService.AddServerAsync(server, cancellationToken);
return CreatedAtAction(nameof(GetServerById), new { id }, server);
}
[HttpPatch("{id}")]
public async Task<IActionResult> UpdateServer(Guid id, ServerDto dto, CancellationToken cancellationToken = default)
{
var updatedId = await serverService.UpdateServerAsync(id, dto.Name, dto.IsHttps, dto.Address, dto.Path, dto.Port, cancellationToken);
return Ok(new { Id = updatedId });
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteServer(Guid id)
{
var deletedId = await serverService.DeleteServerAsync(id);
return Ok(new { Id = deletedId });
}
}
@@ -1,11 +0,0 @@
namespace MonitorPanel.API.Dto;
public class ServerDto
{
public Guid Id { get; set; }
public string Name { get; set; } = string.Empty;
public bool IsHttps { get; set; }
public string Address { get; set; } = string.Empty;
public string? Path { get; set; }
public int Port { get; set; }
}
@@ -1,28 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.2.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MonitorPanel.Core\MonitorPanel.Core.csproj" />
<ProjectReference Include="..\MonitorPanel.DataAccess\MonitorPanel.DataAccess.csproj" />
<ProjectReference Include="..\MonitorPanel.Application\MonitorPanel.Application.csproj" />
</ItemGroup>
</Project>
@@ -1,6 +0,0 @@
@MonitorPanel.API_HostAddress = http://localhost:5068
GET {{MonitorPanel.API_HostAddress}}/weatherforecast/
Accept: application/json
###
@@ -1,40 +0,0 @@
using Microsoft.EntityFrameworkCore;
using MonitorPanel.Core.Abstractions;
using MonitorPanel.DataAccess;
using MonitorPanel.DataAccess.Repositories;
using MonitorPanel.Application.Services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<MonitorPanelDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services
.AddScoped<IServersRepository, ServersRepository>()
.AddScoped<IServerService, ServerService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseSwagger().UseSwaggerUI();
app.Run();
@@ -1,23 +0,0 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5068",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7204;http://localhost:5068",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
@@ -1,9 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
@@ -1,13 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\MonitorPanel.Core\MonitorPanel.Core.csproj" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
@@ -1,32 +0,0 @@
using MonitorPanel.Core.Abstractions;
using MonitorPanel.Core.Models;
namespace MonitorPanel.Application.Services;
public class ServerService(IServersRepository serversRepository) : IServerService
{
public Task<Guid> AddServerAsync(Server server, CancellationToken cancellationToken = default)
{
return serversRepository.AddServerAsync(server, cancellationToken);
}
public Task<Guid> DeleteServerAsync(Guid id, CancellationToken cancellationToken = default)
{
return serversRepository.DeleteServerAsync(id, cancellationToken);
}
public Task<IEnumerable<Server>> GetAllServersAsync(CancellationToken cancellationToken = default)
{
return serversRepository.GetAllServersAsync(cancellationToken);
}
public Task<Server?> GetServerByIdAsync(Guid id, CancellationToken cancellationToken = default)
{
return serversRepository.GetServerByIdAsync(id, cancellationToken);
}
public Task<Guid> UpdateServerAsync(Guid id, string name, bool isHttps, string address, string? path, int port, CancellationToken cancellationToken = default)
{
return serversRepository.UpdateServerAsync(id, name, isHttps, address, path, port, cancellationToken);
}
}
@@ -1,12 +0,0 @@
using MonitorPanel.Core.Models;
namespace MonitorPanel.Core.Abstractions;
public interface IServerService
{
Task<Guid> AddServerAsync(Server server, CancellationToken cancellationToken = default);
Task<Guid> DeleteServerAsync(Guid id, CancellationToken cancellationToken = default);
Task<IEnumerable<Server>> GetAllServersAsync(CancellationToken cancellationToken = default);
Task<Server?> GetServerByIdAsync(Guid id, CancellationToken cancellationToken = default);
Task<Guid> UpdateServerAsync(Guid id, string name, bool isHttps, string address, string? path, int port, CancellationToken cancellationToken = default);
}
@@ -1,11 +0,0 @@
using MonitorPanel.Core.Models;
namespace MonitorPanel.Core.Abstractions;
public interface IServersRepository
{
Task<IEnumerable<Server>> GetAllServersAsync(CancellationToken cancellationToken = default);
Task<Server?> GetServerByIdAsync(Guid id, CancellationToken cancellationToken = default);
Task<Guid> AddServerAsync(Server server, CancellationToken cancellationToken = default);
Task<Guid> UpdateServerAsync(Guid id, string name, bool isHttps, string address, string? path, int port, CancellationToken cancellationToken = default);
Task<Guid> DeleteServerAsync(Guid id, CancellationToken cancellationToken = default);
}
@@ -1,17 +0,0 @@
namespace MonitorPanel.Core.Models;
public class Server(
Guid id,
string name,
string address,
string? path = null,
bool isHttps = true,
int port = 443)
{
public readonly Guid Id = id;
public string Name { get; set; } = name;
public bool IsHttps { get; set; } = isHttps;
public string Address { get; set; } = address;
public string? Path { get; set; } = path;
public int Port { get; set; } = port;
}
@@ -1,9 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
@@ -1,14 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace MonitorPanel.DataAccess.Entities;
public class ServerEntity
{
public Guid Id { get; set; }
public string Name { get; set; } = null!;
public bool IsHttps { get; set; }
[Required]
public string Address { get; set; } = null!;
public string? Path { get; set; }
[Required]
public int Port { get; set; }
}
@@ -1,58 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MonitorPanel.DataAccess;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace MonitorPanel.DataAccess.Migrations
{
[DbContext(typeof(MonitorPanelDbContext))]
[Migration("20260809010527_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("MonitorPanel.DataAccess.Entities.ServerEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Address")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsHttps")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Path")
.HasColumnType("text");
b.Property<int>("Port")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Servers");
});
#pragma warning restore 612, 618
}
}
}
@@ -1,38 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace MonitorPanel.DataAccess.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Servers",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
IsHttps = table.Column<bool>(type: "boolean", nullable: false),
Address = table.Column<string>(type: "text", nullable: false),
Path = table.Column<string>(type: "text", nullable: true),
Port = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Servers", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Servers");
}
}
}
@@ -1,55 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MonitorPanel.DataAccess;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace MonitorPanel.DataAccess.Migrations
{
[DbContext(typeof(MonitorPanelDbContext))]
partial class MonitorPanelDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("MonitorPanel.DataAccess.Entities.ServerEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Address")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsHttps")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Path")
.HasColumnType("text");
b.Property<int>("Port")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Servers");
});
#pragma warning restore 612, 618
}
}
}
@@ -1,26 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MonitorPanel.Core\MonitorPanel.Core.csproj" />
</ItemGroup>
</Project>
@@ -1,8 +0,0 @@
using Microsoft.EntityFrameworkCore;
using MonitorPanel.DataAccess.Entities;
namespace MonitorPanel.DataAccess;
public class MonitorPanelDbContext(DbContextOptions<MonitorPanelDbContext> options) : DbContext(options)
{
public DbSet<ServerEntity> Servers => Set<ServerEntity>();
}
@@ -1,60 +0,0 @@
using Microsoft.EntityFrameworkCore;
using MonitorPanel.Core.Abstractions;
using MonitorPanel.Core.Models;
using MonitorPanel.DataAccess.Entities;
namespace MonitorPanel.DataAccess.Repositories;
public class ServersRepository(MonitorPanelDbContext db) : IServersRepository
{
public async Task<Guid> AddServerAsync(Server server, CancellationToken cancellationToken = default)
{
var entity = new ServerEntity
{
Id = server.Id,
Name = server.Name,
IsHttps = server.IsHttps,
Address = server.Address,
Path = server.Path,
Port = server.Port
};
await db.Servers.AddAsync(entity, cancellationToken);
await db.SaveChangesAsync(cancellationToken);
return entity.Id;
}
public async Task<Guid> DeleteServerAsync(Guid id, CancellationToken cancellationToken = default)
{
await db.Servers.Where(s => s.Id == id).ExecuteDeleteAsync(cancellationToken);
return id;
}
public async Task<IEnumerable<Server>> GetAllServersAsync(CancellationToken cancellationToken = default)
{
return await db.Servers.AsNoTracking()
.Select(s => new Server(s.Id, s.Name, s.Address, s.Path, s.IsHttps, s.Port))
.ToListAsync(cancellationToken);
}
public async Task<Server?> GetServerByIdAsync(Guid id, CancellationToken cancellationToken = default)
{
var entity = await db.Servers.FirstOrDefaultAsync(s => s.Id == id, cancellationToken);
return entity == null ? null : new Server(entity.Id, entity.Name, entity.Address, entity.Path, entity.IsHttps, entity.Port);
}
public async Task<Guid> UpdateServerAsync(Guid id, string name, bool isHttps, string address, string? path, int port, CancellationToken cancellationToken = default)
{
var entity = await db.Servers.FirstOrDefaultAsync(s => s.Id == id, cancellationToken)
?? throw new InvalidOperationException("Server not found");
entity.Name = name;
entity.IsHttps = isHttps;
entity.Address = address;
entity.Path = path;
entity.Port = port;
await db.SaveChangesAsync(cancellationToken);
return entity.Id;
}
}
-6
View File
@@ -1,6 +0,0 @@
<Solution>
<Project Path="MonitorPanel.API/MonitorPanel.API.csproj" />
<Project Path="MonitorPanel.Application/MonitorPanel.Application.csproj" />
<Project Path="MonitorPanel.Core/MonitorPanel.Core.csproj" />
<Project Path="MonitorPanel.DataAccess/MonitorPanel.DataAccess.csproj" />
</Solution>