-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
98 lines (85 loc) · 2.68 KB
/
Copy pathProgram.cs
File metadata and controls
98 lines (85 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using ServerMonitor;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
?? throw new InvalidOperationException(
"Connection string 'DefaultConnection' is not configured. Use user-secrets, environment variables, or appsettings.Development.json.");
builder.Services.AddControllers()
.PartManager.ApplicationParts.Add(new AssemblyPart(typeof(Program).Assembly));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(connectionString));
builder.Services.AddScoped<MonitorService>();
var app = builder.Build();
if(app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapGet("/api/metric", async (MonitorService monitor, AppDbContext db) =>
{
var metric = new Metric
{
RamUsage = monitor.GetRamUsage(),
CpuInfo = monitor.GetCpuPercent(),
DiskUsage = monitor.GetDiskUsage(),
ActiveProcess = monitor.GetProcess(),
Timestamp = DateTime.UtcNow,
ServerId = 1
};
db.Metrics.Add(metric);
if (metric.RamUsage > 85)
{
db.Alerts.Add(new Alertador
{
Message = $"RAM alta: {metric.RamUsage}%",
Level = "Warning",
Tipo = "RAM",
Valor = metric.RamUsage,
CreatedAt = DateTime.UtcNow
});
}
if (metric.CpuInfo > 90)
{
db.Alerts.Add(new Alertador
{
Message = $"CPU alta: {metric.CpuInfo}%",
Level = "Critical",
Tipo = "CPU",
Valor = metric.CpuInfo,
CreatedAt = DateTime.UtcNow
});
}
if (metric.DiskUsage > 80)
{
db.Alerts.Add(new Alertador
{
Message = $"Disco alto: {metric.DiskUsage}%",
Level = "Warning",
Tipo = "Disco",
Valor = metric.DiskUsage,
CreatedAt = DateTime.UtcNow
});
}
await db.SaveChangesAsync();
return Results.Ok(metric);
})
.WithName("GetMetrics")
.WithOpenApi();
app.MapGet("/api/metric/history", async (AppDbContext db) =>
{
return Results.Ok(await db.Metrics.ToListAsync());
});
app.MapGet("/api/alerts", async (AppDbContext db) =>
{
return Results.Ok(await db.Alerts
.OrderByDescending(alert => alert.CreatedAt)
.ToListAsync());
})
.WithName("GetAlerts")
.WithOpenApi();
app.MapControllers();
app.Run();