feat(web): monitoring agents temps réel — cartes jauges live (Fixes #37)

- AgentCard.razor : carte agent avec jauges CPU/RAM/Disque (MudProgressLinear)
  + uptime, seuils (CPU/RAM >90% warning, >95% error), état hors ligne
  (dernier contact), statut traduit en chip, lien vers détail.
- AllAgentsPage : table → grille responsive de cartes (xs1/sm2/md3/xl4) +
  auto-refresh 15s (garde CancellationToken, pause si disposé).
- Dashboard : section 'Charge des agents' en cartes jauges live +
  auto-refresh 15s ciblé agents (stats globales au refresh manuel).
- Dispose() sur les deux pages pour stopper les timers.
- Tests : adaptés à la nouvelle UI + 3 tests AgentCard (jauges, hors
  ligne, seuil CPU). 182 tests Web verts.
This commit is contained in:
Arnaud Dartois committed 2026-08-10 23:26:32 +02:00
1 parent 7b5e14e056
commit ed7df6026b
5 files changed
+311 -87

No files matched your search

+127
View File
@@ -0,0 +1,127 @@
@* AgentCard.razor — carte agent avec jauges live CPU/RAM/Disque/Uptime.
Seuils : CPU/RAM > 90 % → warning, > 95 % → error. Hors ligne → jauges grisées. *@
@using Heimdall.Web.Services
@inject NavigationManager Nav
<MudPaper Elevation="1" Class="pa-4 hmd-tile" Style="border-radius: var(--hmd-radius-md); height: 100%; display:flex; flex-direction:column;">
@* ─── En-tête : nom + statut ─── *@
<div class="d-flex align-center mb-3">
<MudIcon Icon="@(Agent.Status == "Online" ? Icons.Material.Filled.Memory : Icons.Material.Filled.Memory)" Size="Size.Small" Class="mr-2" Color="Color.Secondary" />
<MudLink Href="@($"/agents/{Agent.Id}")" Typo="Typo.subtitle1" Class="font-weight-medium text-truncate" style="flex:1;">
@Agent.Name
</MudLink>
<StatusChip Text="@FormatStatus(Agent.Status)" Color="@GetStatusColor(Agent.Status)"
Icon="@GetStatusIcon(Agent.Status)" Size="Size.Small" />
</div>
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mb-3 text-truncate">
@Agent.Hostname
@if (!string.IsNullOrEmpty(Agent.PublicIp)) { <span> · @Agent.PublicIp</span> }
</MudText>
@if (Agent.Status != "Online")
{
<div class="d-flex align-center justify-center flex-column" style="flex:1; min-height: 120px;">
<MudIcon Icon="@Icons.Material.Filled.CloudOff" Size="Size.Large" Color="Color.Secondary" />
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-2">
@(Agent.Status == "Offline" ? "Agent hors ligne" : "Agent en erreur")
</MudText>
@if (Agent.LastHeartbeat is { } hb)
{
<MudText Typo="Typo.caption" Color="Color.Secondary">
Dernier contact : @hb.ToLocalTime().ToString("g")
</MudText>
}
</div>
}
else
{
<div class="d-flex flex-column" style="gap: 10px;">
@* CPU *@
<div>
<div class="d-flex justify-space-between">
<MudText Typo="Typo.caption">CPU</MudText>
<MudText Typo="Typo.caption" Color="@GetMetricColor(CpuPercent)">@FormatPercent(CpuPercent)</MudText>
</div>
<MudProgressLinear Value="@(CpuPercent ?? 0)" Color="@GetMetricColor(CpuPercent)" Rounded="true" Size="Size.Small" />
</div>
@* RAM *@
<div>
<div class="d-flex justify-space-between">
<MudText Typo="Typo.caption">Mémoire</MudText>
<MudText Typo="Typo.caption" Color="@GetMetricColor(MemoryPercent)">@FormatPercent(MemoryPercent)</MudText>
</div>
<MudProgressLinear Value="@(MemoryPercent ?? 0)" Color="@GetMetricColor(MemoryPercent)" Rounded="true" Size="Size.Small" />
</div>
@* Disque *@
<div>
<div class="d-flex justify-space-between">
<MudText Typo="Typo.caption">Disque</MudText>
<MudText Typo="Typo.caption" Color="@GetMetricColor(DiskPercent)">@FormatPercent(DiskPercent)</MudText>
</div>
<MudProgressLinear Value="@(DiskPercent ?? 0)" Color="@GetMetricColor(DiskPercent)" Rounded="true" Size="Size.Small" />
</div>
@* Uptime *@
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mt-1">
<MudIcon Icon="@Icons.Material.Filled.Schedule" Size="Size.Small" Class="mr-1" /> Uptime : @FormatUptime()
</MudText>
</div>
}
</MudPaper>
@code {
[Parameter, EditorRequired] public AgentItem Agent { get; set; } = default!;
private double? CpuPercent => Agent.CpuUsagePercent is { } c ? Math.Clamp(c, 0, 100) : null;
private double? DiskPercent => Agent.DiskUsagePercent is { } d ? Math.Clamp(d, 0, 100) : null;
private double? MemoryPercent
{
get
{
if (Agent.MemoryMb <= 0) return null;
var usedMb = Agent.MemoryUsageBytes is { } b ? b / 1024.0 / 1024.0 : 0;
return Math.Clamp(usedMb / Agent.MemoryMb * 100, 0, 100);
}
}
private static Color GetStatusColor(string status) => status switch
{
"Online" => Color.Success,
"Offline" => Color.Error,
"Error" => Color.Warning,
_ => Color.Default
};
private static string GetStatusIcon(string status) => status switch
{
"Online" => Icons.Material.Filled.CheckCircle,
"Offline" => Icons.Material.Filled.Cancel,
"Error" => Icons.Material.Filled.Warning,
_ => Icons.Material.Filled.Help
};
private static string FormatStatus(string status) => status switch
{
"Online" => "En ligne",
"Offline" => "Hors ligne",
"Error" => "Erreur",
_ => status
};
private static string FormatPercent(double? v) => v is { } p ? $"{p:F0}%" : "—";
private static Color GetMetricColor(double? v) => v switch
{
> 95 => Color.Error,
> 90 => Color.Warning,
_ => Color.Success
};
private string FormatUptime()
{
if (Agent.UptimeSeconds is not { } s) return "—";
var t = TimeSpan.FromSeconds(s);
return t.TotalDays >= 1 ? $"{(int)t.TotalDays}j {t.Hours}h" : $"{t.Hours}h {t.Minutes}min";
}
}
@@ -58,48 +58,16 @@ else
}
else
{
<MudTable Items="@_agents" Hover="true" Striped="true" Elevation="2">
<HeaderContent>
<MudTh>Nom</MudTh>
<MudTh>Site</MudTh>
<MudTh>Hostname</MudTh>
<MudTh>Version</MudTh>
<MudTh>Statut</MudTh>
<MudTh>Dernier heartbeat</MudTh>
<MudTh>IP</MudTh>
<MudTh>Actions</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Nom">
<MudLink Href="@($"/agents/{context.Id}")">@context.Name</MudLink>
</MudTd>
<MudTd DataLabel="Site">
<MudLink Href="@($"/sites/{context.SiteId}")">@context.SiteName</MudLink>
</MudTd>
<MudTd DataLabel="Hostname">@context.Hostname</MudTd>
<MudTd DataLabel="Version">@context.Version</MudTd>
<MudTd DataLabel="Statut">
<StatusChip Text="@context.Status"
Color="@GetStatusColor(context.Status)"
Icon="@GetStatusIcon(context.Status)" />
</MudTd>
<MudTd DataLabel="Dernier heartbeat">
@(context.LastHeartbeat?.ToString("g") ?? "Jamais")
</MudTd>
<MudTd DataLabel="IP">@context.PublicIp</MudTd>
<MudTd DataLabel="Actions">
<MudTooltip Text="Voir le détail de l'agent">
<MudIconButton Icon="@Icons.Material.Filled.Visibility" Size="Size.Small" aria-label="Voir les détails"
OnClick="@(() => Nav.NavigateTo($"/agents/{context.Id}"))" />
</MudTooltip>
</MudTd>
</RowTemplate>
<ChildRowContent>
<MudTd ColSpan="8">
<AgentMetrics Agent="@context" />
</MudTd>
</ChildRowContent>
</MudTable>
<MudContainer MaxWidth="MaxWidth.False" Class="px-0">
<MudGrid>
@foreach (var agent in _agents)
{
<MudItem xs="12" sm="6" md="4" xl="3" @key="agent.Id">
<AgentCard Agent="@agent" />
</MudItem>
}
</MudGrid>
</MudContainer>
@* ─── Pagination ─── *@
<PaginationBar Page="@_page"
@@ -122,7 +90,41 @@ else
[Inject] private NavigationManager Nav { get; set; } = null!;
protected override async Task OnInitializedAsync() => await LoadData();
protected override async Task OnInitializedAsync()
{
await LoadData();
await StartAutoRefresh();
}
// ─── Auto-refresh 15s (métriques live) ─────────────────────────
private CancellationTokenSource? _refreshCts;
private bool _disposed;
private async Task StartAutoRefresh()
{
_refreshCts = new CancellationTokenSource();
try
{
while (!_refreshCts.Token.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(15), _refreshCts.Token);
if (_disposed) return;
try
{
var result = await Api.GetAllAgentsAsync(_page);
if (result is not null)
{
_agents = result.Items;
_total = result.TotalCount;
_totalPages = Math.Max(1, (int)Math.Ceiling(result.TotalCount / (double)result.PageSize));
}
if (!_disposed) await InvokeAsync(StateHasChanged);
}
catch { /* keep last state */ }
}
}
catch (OperationCanceledException) { /* arrêt volontaire */ }
}
private async Task LoadData()
{
@@ -159,19 +161,10 @@ else
await LoadData();
}
private static Color GetStatusColor(string status) => status switch
public void Dispose()
{
"Online" => Color.Success,
"Offline" => Color.Error,
"Error" => Color.Warning,
_ => Color.Default
};
private static string GetStatusIcon(string status) => status switch
{
"Online" => Icons.Material.Filled.CheckCircle,
"Offline" => Icons.Material.Filled.Cancel,
"Error" => Icons.Material.Filled.Warning,
_ => Icons.Material.Filled.Help
};
_disposed = true;
_refreshCts?.Cancel();
_refreshCts?.Dispose();
}
}
@@ -161,33 +161,27 @@
</MudText>
@if (_agentsLoading)
{
<MudSkeleton Width="100%" Height="60px" />
<MudGrid>
@for (var i = 0; i < 2; i++)
{
<MudItem xs="12" sm="6">
<MudPaper Elevation="0" Style="border-radius: var(--hmd-radius-md);">
<MudSkeleton Variant="SkeletonVariant.Rectangular" Height="140px" />
</MudPaper>
</MudItem>
}
</MudGrid>
}
else if (_agents is { Count: > 0 })
{
<MudTable Items="@_agents" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>Agent</MudTh>
<MudTh>Dernier heartbeat</MudTh>
<MudTh>Statut</MudTh>
<MudTh>GPU</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd><MudLink Href="@($"/agents/{context.Id}")">@context.Name</MudLink></MudTd>
<MudTd><MudText Typo="Typo.body2">@(context.LastHeartbeat?.ToLocalTime().ToString("g") ?? "—")</MudText></MudTd>
<MudTd><MudText Color="@(context.Status == "Online" ? Color.Success : Color.Error)">@context.Status</MudText></MudTd>
<MudTd>
@if (context.HasGpu)
{
<MudIcon Icon="@Icons.Material.Filled.Memory" Color="Color.Success" Size="Size.Small" />
}
else
{
<MudText Typo="Typo.body2" Color="Color.Default">—</MudText>
}
</MudTd>
</RowTemplate>
</MudTable>
<MudGrid>
@foreach (var agent in _agents)
{
<MudItem xs="12" sm="6" @key="agent.Id">
<AgentCard Agent="@agent" />
</MudItem>
}
</MudGrid>
<MudLink Href="/admin/agents" Typo="Typo.caption" Class="mt-2 d-block">Tous les agents →</MudLink>
}
else
@@ -310,7 +304,43 @@
new("Désactivée", 0, Color.Default, 0),
];
protected override async Task OnInitializedAsync() => await LoadData();
protected override async Task OnInitializedAsync()
{
await LoadData();
await StartAutoRefresh();
}
// ─── Auto-refresh 15s (métriques agents) ─────────────────────────
private CancellationTokenSource? _refreshCts;
private bool _disposed;
private async Task StartAutoRefresh()
{
_refreshCts = new CancellationTokenSource();
try
{
while (!_refreshCts.Token.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(15), _refreshCts.Token);
if (_disposed) return;
// Rafraîchit uniquement la section agents (léger) : les stats
// globales restent au refresh manuel pour éviter le flash.
try
{
_agentsLoading = true;
var agentsPage = await Api.GetAllAgentsAsync(1, 5);
_agents = agentsPage?.Items?.ToList();
}
catch { /* keep last state */ }
finally
{
_agentsLoading = false;
if (!_disposed) await InvokeAsync(StateHasChanged);
}
}
}
catch (OperationCanceledException) { /* arrêt volontaire */ }
}
private async Task LoadData()
{
@@ -377,4 +407,11 @@
};
private record CameraStatusEntry(string Label, int Count, Color Color, int Percent);
public void Dispose()
{
_disposed = true;
_refreshCts?.Cancel();
_refreshCts?.Dispose();
}
}
@@ -0,0 +1,66 @@
using Bunit;
using Heimdall.Web.Components;
using Heimdall.Web.Services;
using Heimdall.Web.Tests.Components.Pages;
using Shouldly;
namespace Heimdall.Web.Tests.Components;
public class AgentCardTests : PageTestBase
{
private static AgentItem Agent(string status = "Online", double? cpu = 35, double? disk = 50, long? memBytes = null) => new()
{
Id = Guid.NewGuid(),
SiteId = Guid.NewGuid(),
SiteName = "Site Alpha",
Name = "Agent-1",
Hostname = "agent-1",
Version = "1.2.3",
Status = status,
LastHeartbeat = DateTime.UtcNow.AddMinutes(-1),
PublicIp = "10.0.0.5",
CpuCores = 4,
MemoryMb = 8192,
CpuUsagePercent = cpu,
DiskUsagePercent = disk,
MemoryUsageBytes = memBytes ?? 4096L * 1024 * 1024,
UptimeSeconds = 90000
};
[Fact]
public void AgentCard_AfficheJaugesEtUptime()
{
var cut = Render<AgentCard>(p => p.Add(x => x.Agent, Agent()));
cut.Markup.ShouldContain("Agent-1");
cut.Markup.ShouldContain("agent-1");
cut.Markup.ShouldContain("En ligne");
cut.Markup.ShouldContain("CPU");
cut.Markup.ShouldContain("Mémoire");
cut.Markup.ShouldContain("Disque");
cut.Markup.ShouldContain("Uptime");
// 35% CPU affiché
cut.Markup.ShouldContain("35%");
}
[Fact]
public void AgentCard_HorsLigne_AfficheEtatSansJauges()
{
var cut = Render<AgentCard>(p => p.Add(x => x.Agent, Agent("Offline")));
cut.Markup.ShouldContain("Hors ligne");
cut.Markup.ShouldContain("Agent hors ligne");
cut.Markup.ShouldNotContain("Uptime");
}
[Fact]
public void AgentCard_CpuEleve_StatutAlerte()
{
// CPU 96% → couleur error (progress bar rouge)
var cut = Render<AgentCard>(p => p.Add(x => x.Agent, Agent(cpu: 96)));
cut.Markup.ShouldContain("96%");
// La progress bar porte la classe de couleur erreur
cut.Markup.ShouldContain("mud-progress-linear");
}
}
@@ -15,7 +15,7 @@ public class AllAgentsPageTests : PageTestBase
private static AgentItem Agent(string name = "Agent-1", string siteName = "Site Alpha") => new()
{
Id = AgentId,
Id = Guid.NewGuid(),
SiteId = SiteId,
SiteName = siteName,
Name = name,
@@ -47,10 +47,11 @@ public class AllAgentsPageTests : PageTestBase
{
cut.Markup.ShouldContain("Agent-1");
cut.Markup.ShouldContain("Agent-2");
cut.Markup.ShouldContain("Site Alpha");
cut.Markup.ShouldContain("Site Beta");
cut.Markup.ShouldContain("1.2.3");
cut.Markup.ShouldContain("Online");
cut.Markup.ShouldContain("agent-1");
cut.Markup.ShouldContain("10.0.0.5");
// Statut traduit sur la carte (StatusChip)
cut.Markup.ShouldContain("En ligne");
// KPI cards
cut.Markup.ShouldContain("Agents");
cut.Markup.ShouldContain("En ligne");
});