Files
Heimdall/src/Heimdall.Web/Components/Pages/AgentDetail.razor
T
Arnaud Dartois c8c84f0e2c
Heimdall Gitea / Build and tests (pull_request) Failing after 3m28s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
feat(inventory): add metric history dashboards
2026-10-25 02:19:01 +02:00

1366 lines
60 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
@page "/agents/{Id:guid}"
@attribute [Authorize(Policy = "Admin.Users")]
@layout MainLayout
@inject HeimdallApiClient Api
@inject ISnackbar Snackbar
@inject NavigationManager Nav
@implements IAsyncDisposable
<MudText Typo="Typo.h1" Class="mb-6">
<MudIcon Icon="@Icons.Material.Filled.Dns" Class="mr-2" />
Agent : @_agent?.Name
</MudText>
@if (_loading)
{
<LoadingSkeleton LineCount="6" />
}
else if (_agent is null)
{
<EmptyState Icon="@Icons.Material.Filled.Dns"
Title="Agent introuvable"
Description="L'agent demandé n'existe pas ou a été supprimé.">
<ActionContent>
<MudButton Variant="Variant.Outlined" Color="Color.Primary"
OnClick="@(() => Nav.NavigateTo("/admin/agents"))">
<MudIcon Icon="@Icons.Material.Filled.ArrowBack" Class="mr-1" /> Retour aux agents
</MudButton>
</ActionContent>
</EmptyState>
}
else
{
@* ─── Status Bar ─── *@
<div class="d-flex align-center mb-4">
<StatusChip Text="@UiFormat.Status(_agent.Status)"
Color="@GetStatusColor(_agent.Status)"
Icon="@GetStatusIcon(_agent.Status)"
Size="Size.Medium" />
<MudSpacer />
<MudText Typo="Typo.body2" Color="Color.Secondary">
Dernier heartbeat : @(_agent.LastHeartbeat?.ToString("g") ?? "Jamais")
</MudText>
</div>
<MudGrid>
<MudItem xs="12" md="6">
<SectionCard Title="Informations" Icon="@Icons.Material.Filled.Info" Elevation="2">
<MudGrid>
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Hostname</MudText>
<MudText Typo="Typo.body1">@_agent.Hostname</MudText>
</MudItem>
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Version</MudText>
<MudText Typo="Typo.body1">@_agent.Version</MudText>
</MudItem>
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Statut</MudText>
<MudText Color="@GetStatusColor(_agent.Status)" Typo="Typo.body1">
@GetStatusIcon(_agent.Status) @_agent.Status
</MudText>
</MudItem>
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">IP publique</MudText>
<MudText Typo="Typo.body1">@(_agent.PublicIp ?? "-")</MudText>
</MudItem>
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Dernier heartbeat</MudText>
<MudText Typo="Typo.body1">@(_agent.LastHeartbeat?.ToString("g") ?? "Jamais")</MudText>
</MudItem>
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Enregistré le</MudText>
<MudText Typo="Typo.body1">@_agent.CreatedAt.ToString("g")</MudText>
</MudItem>
</MudGrid>
</SectionCard>
</MudItem>
<MudItem xs="12" md="6">
<SectionCard Title="Capacités" Icon="@Icons.Material.Filled.Dns" Elevation="2">
<MudGrid>
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">CPU</MudText>
<MudText Typo="Typo.body1">@_agent.CpuCores cœurs</MudText>
</MudItem>
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Mémoire</MudText>
<MudText Typo="Typo.body1">@FormatMemory(_agent.MemoryMb)</MudText>
</MudItem>
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">GPU</MudText>
<MudText Typo="Typo.body1">
<MudIcon Icon="@(_agent.HasGpu ? Icons.Material.Filled.CheckCircle : Icons.Material.Filled.Cancel)"
Color="@(_agent.HasGpu ? Color.Success : Color.Default)" Size="Size.Small" />
@(_agent.HasGpu ? _agent.GpuType : "Aucun")
</MudText>
</MudItem>
</MudGrid>
</SectionCard>
</MudItem>
</MudGrid>
@* ─── Hardware Inventory ─── *@
<MudGrid Class="mt-4">
@* ─── CPU Inventory ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Processeur" Icon="@Icons.Material.Filled.Memory" Elevation="2">
<MudGrid>
@if (_agent.CpuModel is not null)
{
<MudItem xs="12">
<MudText Typo="Typo.body2" Color="Color.Secondary">Modèle</MudText>
<MudText Typo="Typo.body1" Class="font-weight-medium">@_agent.CpuModel</MudText>
</MudItem>
}
@if (_agent.CpuVendor is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Fabricant</MudText>
<MudText Typo="Typo.body1">@_agent.CpuVendor</MudText>
</MudItem>
}
@if (_agent.CpuArchitecture is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Architecture</MudText>
<MudText Typo="Typo.body1">@_agent.CpuArchitecture</MudText>
</MudItem>
}
@if (_agent.PhysicalCores.HasValue)
{
<MudItem xs="4">
<MudText Typo="Typo.body2" Color="Color.Secondary">Cœurs physiques</MudText>
<MudText Typo="Typo.body1">@_agent.PhysicalCores</MudText>
</MudItem>
}
@if (_agent.LogicalCores.HasValue)
{
<MudItem xs="4">
<MudText Typo="Typo.body2" Color="Color.Secondary">Cœurs logiques</MudText>
<MudText Typo="Typo.body1">@_agent.LogicalCores</MudText>
</MudItem>
}
@if (_agent.ThreadsPerCore.HasValue)
{
<MudItem xs="4">
<MudText Typo="Typo.body2" Color="Color.Secondary">Threads/noyau</MudText>
<MudText Typo="Typo.body1">@_agent.ThreadsPerCore</MudText>
</MudItem>
}
@if (_agent.CpuFrequencyMhz.HasValue)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Fréquence</MudText>
<MudText Typo="Typo.body1">@($"{_agent.CpuFrequencyMhz:F0} MHz")</MudText>
</MudItem>
}
@if (_agent.CpuCacheBytes.HasValue && _agent.CpuCacheBytes > 0)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Cache</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.CpuCacheBytes.Value)</MudText>
</MudItem>
}
@if (!string.IsNullOrEmpty(_agent.CpuFlags))
{
<MudItem xs="12" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Instructions clés</MudText>
<div class="d-flex flex-wrap gap-1 mt-1">
@foreach (var flag in _agent.CpuFlags.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
<MudChip T="string" Size="Size.Small" Color="Color.Info" Variant="Variant.Outlined">@flag</MudChip>
}
</div>
</MudItem>
}
</MudGrid>
</SectionCard>
</MudItem>
@* ─── Memory & Disk Inventory ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Mémoire & Stockage" Icon="@Icons.Material.Filled.Storage" Elevation="2">
<MudGrid>
@if (_agent.MemTotalBytes.HasValue)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Mémoire totale</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.MemTotalBytes.Value)</MudText>
</MudItem>
}
@if (_agent.MemAvailableBytes.HasValue)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Mémoire dispo</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.MemAvailableBytes.Value)</MudText>
</MudItem>
}
@if (_agent.SwapTotalBytes.HasValue && _agent.SwapTotalBytes > 0)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Swap total</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.SwapTotalBytes.Value)</MudText>
</MudItem>
}
@if (_agent.SwapFreeBytes.HasValue && _agent.SwapTotalBytes is > 0)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Swap dispo</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.SwapFreeBytes.Value)</MudText>
</MudItem>
}
@if (_agent.ContainerMemoryLimitBytes.HasValue)
{
<MudItem xs="12" Class="mt-2">
<MudChip T="string" Size="Size.Small" Color="Color.Warning">
Limite conteneur : @FormatBytes(_agent.ContainerMemoryLimitBytes.Value)
</MudChip>
</MudItem>
}
@if (!string.IsNullOrEmpty(_agent.DiskInventoryJson))
{
<MudItem xs="12" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Disques</MudText>
@{
var disks = ParseDiskJson(_agent.DiskInventoryJson);
}
@if (disks.Count > 0)
{
<MudTable Items="@disks" Dense="true" Hover="true" Elevation="0" Class="mt-1">
<HeaderContent>
<MudTh>Point de montage</MudTh>
<MudTh>FS</MudTh>
<MudTh>Taille</MudTh>
<MudTh>Utilisé</MudTh>
<MudTh>Type</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Point de montage">
<MudText Typo="Typo.body2">@context.MountPoint</MudText>
</MudTd>
<MudTd DataLabel="FS">
<MudText Typo="Typo.body2">@context.FileSystem</MudText>
</MudTd>
<MudTd DataLabel="Taille">
<MudText Typo="Typo.body2">@(context.TotalBytes.HasValue ? FormatBytes(context.TotalBytes.Value) : "-")</MudText>
</MudTd>
<MudTd DataLabel="Utilisé">
<MudText Typo="Typo.body2">@(context.UsedBytes.HasValue ? FormatBytes(context.UsedBytes.Value) : "-")</MudText>
</MudTd>
<MudTd DataLabel="Type">
<MudChip T="string" Size="Size.Small"
Color="@(context.Type == "SSD" ? Color.Success : Color.Default)">
@context.Type
</MudChip>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-1">Aucun disque détecté</MudText>
}
</MudItem>
}
</MudGrid>
</SectionCard>
</MudItem>
</MudGrid>
<MudGrid Class="mt-4">
@* ─── GPU Inventory ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="GPU" Icon="@Icons.Material.Filled.Videocam" Elevation="2">
@{
var gpus = ParseGpuJson(_agent.GpuInventoryJson);
}
@if (gpus.Count > 0)
{
<MudTable Items="@gpus" Dense="true" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>Modèle</MudTh>
<MudTh>Backend</MudTh>
<MudTh>VRAM</MudTh>
<MudTh>Temp</MudTh>
<MudTh>Utilisation</MudTh>
<MudTh>Driver</MudTh>
<MudTh>Encoder</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Modèle">
<MudText Typo="Typo.body2" Class="font-weight-medium">@(context.Model ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="Backend">
<MudChip T="string" Size="Size.Small" Color="Color.Info">@(context.Backend ?? "-")</MudChip>
</MudTd>
<MudTd DataLabel="VRAM">
<MudText Typo="Typo.body2">@(context.VramBytes.HasValue ? FormatBytes(context.VramBytes.Value) : "-")</MudText>
</MudTd>
<MudTd DataLabel="Temp">
<MudText Typo="Typo.body2">@(context.TemperatureCelsius.HasValue ? $"{context.TemperatureCelsius:F0}°C" : "-")</MudText>
</MudTd>
<MudTd DataLabel="Utilisation">
<MudText Typo="Typo.body2">@(context.UtilizationPercent.HasValue ? $"{context.UtilizationPercent:F0}%" : "-")</MudText>
</MudTd>
<MudTd DataLabel="Driver">
<MudText Typo="Typo.body2">@(context.DriverVersion ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="Encoder">
<MudText Typo="Typo.body2">@(context.EncoderSupport ?? "-")</MudText>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">Aucun GPU détecté</MudText>
}
</SectionCard>
</MudItem>
@* ─── Host & Container ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Système & Conteneur" Icon="@Icons.Material.Filled.Computer" Elevation="2">
<MudGrid>
@if (_agent.OsName is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">OS</MudText>
<MudText Typo="Typo.body1">@_agent.OsName</MudText>
</MudItem>
}
@if (_agent.KernelVersion is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Noyau</MudText>
<MudText Typo="Typo.body1">@_agent.KernelVersion</MudText>
</MudItem>
}
@if (_agent.Arch is not null)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Architecture</MudText>
<MudText Typo="Typo.body1">@_agent.Arch</MudText>
</MudItem>
}
@if (_agent.UptimeMachineSeconds.HasValue)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Uptime machine</MudText>
<MudText Typo="Typo.body1">@FormatUptime(_agent.UptimeMachineSeconds.Value)</MudText>
</MudItem>
}
@if (_agent.ContainerId is not null)
{
<MudItem xs="12" Class="mt-2">
<MudDivider Class="mb-2" />
<MudText Typo="Typo.body2" Color="Color.Secondary">Conteneur</MudText>
<MudText Typo="Typo.body1">
<MudIcon Icon="@Icons.Material.Filled.CheckCircle" Color="Color.Success" Size="Size.Small" Class="mr-1" />
@(_agent.ContainerImage ?? "Conteneur Docker")
</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">ID: @_agent.ContainerId</MudText>
</MudItem>
}
@if (_agent.ContainerCpuLimit.HasValue)
{
<MudItem xs="6" Class="mt-2">
<MudChip T="string" Size="Size.Small" Color="Color.Warning">
CPU limite: @($"{_agent.ContainerCpuLimit.Value / 100.0:F1} cores")
</MudChip>
</MudItem>
}
</MudGrid>
</SectionCard>
</MudItem>
</MudGrid>
<MudGrid Class="mt-4">
@* ─── Network Interfaces ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Réseau" Icon="@Icons.Material.Filled.Wifi" Elevation="2">
@{
var interfaces = ParseNetworkJson(_agent.NetworkInterfacesJson);
}
@if (interfaces.Count > 0)
{
<MudTable Items="@interfaces" Dense="true" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>Interface</MudTh>
<MudTh>Adresse IP</MudTh>
<MudTh>MAC</MudTh>
<MudTh>Débit</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Interface">
<MudText Typo="Typo.body2" Class="font-weight-medium">@context.Name</MudText>
</MudTd>
<MudTd DataLabel="Adresse IP">
<MudText Typo="Typo.body2">@(context.IpAddress ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="MAC">
<MudText Typo="Typo.body2">@(context.MacAddress ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="Débit">
<MudText Typo="Typo.body2">@(context.SpeedMbps.HasValue ? $"{context.SpeedMbps} Mbps" : "-")</MudText>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">Aucune interface réseau détectée</MudText>
}
</SectionCard>
</MudItem>
@* ─── Temperature ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Températures" Icon="@Icons.Material.Filled.Thermostat" Elevation="2">
@{
var temps = ParseTemperatureJson(_agent.TemperatureJson);
}
@if (temps.Count > 0)
{
<MudTable Items="@temps" Dense="true" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>Zone</MudTh>
<MudTh>Température</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Zone">
<MudText Typo="Typo.body2">@context.Zone</MudText>
</MudTd>
<MudTd DataLabel="Température">
@{
Color tempColor;
if (context.TemperatureCelsius > 70)
tempColor = Color.Error;
else if (context.TemperatureCelsius > 50)
tempColor = Color.Warning;
else
tempColor = Color.Default;
}
<MudText Typo="Typo.body2" Color="@tempColor">
@($"{context.TemperatureCelsius:F1}°C")
</MudText>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">Aucune sonde de température détectée</MudText>
}
</SectionCard>
</MudItem>
</MudGrid>
@* ─── Agent Settings (globals hérités + overrides) ─── *@
<SectionCard Title="Configuration"
Icon="@Icons.Material.Filled.Tune"
Elevation="2"
HelpText="Paramètres globaux hérités par cet agent, modifiables pour ce site uniquement. Envoyés en temps réel via SignalR.">
@if (_settingsLoading)
{
<MudProgressCircular Indeterminate="true" Size="Size.Small" />
}
else if (_settingsError)
{
<MudAlert Severity="Severity.Error" Class="mb-4">
Erreur lors du chargement de la configuration
<MudButton OnClick="@LoadSettingsAsync" Size="Size.Small" Variant="Variant.Text" Class="ml-2">Réessayer</MudButton>
</MudAlert>
}
else if (_globalSettings.Count == 0 && _settings.Count == 0)
{
<MudAlert Severity="Severity.Info" Class="mb-4">
Aucun paramètre global exposé aux agents pour le moment.
</MudAlert>
}
else
{
@foreach (var category in _globalSettings.GroupBy(s => s.Category).OrderBy(g => g.Key))
{
<div class="settings-category mb-4" @key="category.Key">
<div class="d-flex align-center mb-2 mt-2">
<MudText Typo="Typo.h6" Class="flex-grow-1">
<MudIcon Icon="@GetAgentCategoryIcon(category.Key)" Size="Size.Small" Class="mr-1" />
@category.Key
</MudText>
<MudChip T="string" Size="Size.Small" Variant="Variant.Outlined">@category.Count()</MudChip>
</div>
<MudGrid>
@foreach (var setting in category)
{
var overridden = IsOverridden(setting.Key);
var effectiveValue = EffectiveValue(setting.Key, setting.Value);
<MudItem xs="12" sm="6" lg="4" @key="setting.Key">
<MudPaper Elevation="1" Class="pa-4 settings-card" Style="border-radius: 12px; height: 100%;">
<div class="d-flex align-center mb-2">
<MudIcon Icon="@GetAgentTypeIcon(setting.ValueType)" Size="Size.Small"
Color="@GetAgentTypeColor(setting.ValueType)" Class="mr-2" />
<div class="flex-grow-1">
<MudText Typo="Typo.body1" Class="font-weight-medium settings-label">
@(setting.Description ?? HumanizeAgentKey(setting.Key))
</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">
@(overridden ? "Valeur surchargée pour cet agent" : "Valeur globale appliquée")
</MudText>
</div>
@if (overridden)
{
<MudTooltip Text="Réinitialiser à la valeur globale">
<MudIconButton Icon="@Icons.Material.Filled.Restore" Size="Size.Small" aria-label="Restaurer"
Color="Color.Warning" OnClick="@(() => ExecuteRemoveSettingByKey(setting.Key))" />
</MudTooltip>
}
</div>
@if (overridden)
{
<MudChip T="string" Size="Size.Small" Color="Color.Warning" Class="mb-2">
Surchargé pour cet agent
</MudChip>
}
else
{
<MudChip T="string" Size="Size.Small" Color="Color.Info" Class="mb-2">
Hérité (global)
</MudChip>
}
@switch (setting.ValueType.ToLowerInvariant())
{
case "boolean":
case "bool":
<div class="d-flex align-center">
<MudSwitch T="bool"
Value="@(effectiveValue?.Equals("true", StringComparison.OrdinalIgnoreCase) == true)"
ValueChanged="@(v => SaveGlobalOverrideBoolAsync(setting, v))"
Color="Color.Primary" Class="flex-grow-1" />
<MudText Typo="Typo.body2" Color="Color.Primary" Class="font-weight-medium">
@(effectiveValue?.Equals("true", StringComparison.OrdinalIgnoreCase) == true ? "Activé" : "Désactivé")
</MudText>
</div>
break;
case "number":
case "int":
case "integer":
case "double":
<MudTextField T="string" Value="@effectiveValue" Variant="Variant.Outlined" Dense="true"
ValueChanged="@(v => SaveGlobalOverrideAsync(setting, v))"
Label="Valeur" Type="InputType.Number" />
break;
case "select":
case "dropdown":
<MudSelect T="string" Value="@effectiveValue" Variant="Variant.Outlined" Dense="true"
ValueChanged="@(v => SaveGlobalOverrideAsync(setting, v))" Label="Valeur">
@foreach (var opt in (setting.AllowedValues ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
<MudSelectItem Value="@opt" @key="opt">@opt</MudSelectItem>
}
</MudSelect>
break;
default:
<MudTextField T="string" Value="@effectiveValue" Variant="Variant.Outlined" Dense="true"
ValueChanged="@(v => SaveGlobalOverrideAsync(setting, v))" Label="Valeur" />
break;
}
</MudPaper>
</MudItem>
}
</MudGrid>
</div>
}
}
@if (_settings.Count > 0)
{
<MudAlert Severity="Severity.Warning" Class="mt-2">
@_settings.Count réglage(s) surchargé(s) pour cet agent — la valeur globale est ignorée pour ces clés.
</MudAlert>
}
</SectionCard>
<MudPaper Elevation="2" Class="pa-6 mb-6" Style="border-radius: 12px;">
<div class="d-flex flex-wrap justify-space-between align-center mb-4">
<MudText Typo="Typo.h6">Historique des ressources</MudText>
<MudButtonGroup Variant="Variant.Outlined" Color="Color.Primary">
<MudButton OnClick="@(() => LoadMetricHistoryAsync("24h"))" Disabled="@(_metricHistoryLoading || _metricRange == "24h")">24 h</MudButton>
<MudButton OnClick="@(() => LoadMetricHistoryAsync("7d"))" Disabled="@(_metricHistoryLoading || _metricRange == "7d")">7 jours</MudButton>
</MudButtonGroup>
</div>
@if (_metricHistoryLoading)
{
<MudProgressLinear Indeterminate="true" />
}
else if (_metricHistoryError)
{
<MudAlert Severity="Severity.Error">Impossible de charger l’historique des ressources.</MudAlert>
}
else
{
@if (_metricHistory.LastOrDefault(point => point.InventoryObservedAtUtc.HasValue) is { } inventoryPoint)
{
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mb-3">
Dernier inventaire GPU/température reçu : @inventoryPoint.InventoryObservedAtUtc!.Value.ToLocalTime().ToString("g").
</MudText>
}
<MudGrid>
<MudItem xs="12" md="6"><MetricHistoryChart Title="CPU utilisé" Points="@MetricSeries(point => point.CpuUsagePercent)" Minimum="0" Maximum="100" /></MudItem>
<MudItem xs="12" md="6"><MetricHistoryChart Title="Mémoire système utilisée" Points="@MetricSeries(MemoryUsedPercent)" Minimum="0" Maximum="100" /></MudItem>
<MudItem xs="12" md="6"><MetricHistoryChart Title="Disque utilisé" Points="@MetricSeries(point => point.DiskUsagePercent)" Minimum="0" Maximum="100" /></MudItem>
<MudItem xs="12" md="6"><MetricHistoryChart Title="Température GPU moyenne" Points="@MetricSeries(point => point.GpuTemperatureCelsius)" Unit=" °C" /></MudItem>
</MudGrid>
}
</MudPaper>
@* ─── Agent Logs ─── *@
<SectionCard Title="Logs"
Icon="@Icons.Material.Filled.ReceiptLong"
Elevation="2"
HelpText="Logs remontés par l'agent, purgés quotidiennement (rétention 7 jours).">
<ChildContent>
<div class="d-flex flex-wrap gap-2 mb-4">
<MudSelect T="string" @bind-Value="_logLevel" Label="Niveau" Variant="Variant.Outlined"
Dense="true" Clearable="true" Class="logs-level-filter" Immediate="true">
<MudSelectItem T="string" Value="@null">Tous les niveaux</MudSelectItem>
<MudSelectItem Value="@("Critical")">Critical</MudSelectItem>
<MudSelectItem Value="@("Error")">Error</MudSelectItem>
<MudSelectItem Value="@("Warning")">Warning</MudSelectItem>
<MudSelectItem Value="@("Information")">Information</MudSelectItem>
<MudSelectItem Value="@("Debug")">Debug</MudSelectItem>
<MudSelectItem Value="@("Trace")">Trace</MudSelectItem>
</MudSelect>
<MudTextField T="string" @bind-Value="_logSearch" Label="Recherche" Variant="Variant.Outlined"
Dense="true" Immediate="true" Class="logs-search-filter"
Placeholder="Message ou source..." />
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => LoadLogsAsync(keepPage: false))"
StartIcon="@Icons.Material.Filled.Search" Class="align-self-center">
Filtrer
</MudButton>
</div>
@if (_logsLoading)
{
<MudPaper Elevation="1" Class="pa-4" Style="border-radius: 8px;">
<MudSkeleton Width="100%" Height="40px" />
<MudSkeleton Width="100%" Height="40px" Class="mt-1" />
<MudSkeleton Width="100%" Height="40px" Class="mt-1" />
</MudPaper>
}
else if (_logsError)
{
<MudAlert Severity="Severity.Error" Class="mb-4" Variant="Variant.Filled">
<MudText>Erreur lors du chargement des logs.</MudText>
<MudButton Variant="Variant.Text" Color="Color.Inherit"
OnClick="@(() => LoadLogsAsync(keepPage: true))" Class="mt-2">
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> Réessayer
</MudButton>
</MudAlert>
}
else
{
<MudTable Items="@_logs" Hover="true" Striped="true" Elevation="2" Dense="true">
<HeaderContent>
<MudTh>Date</MudTh>
<MudTh>Niveau</MudTh>
<MudTh>Source</MudTh>
<MudTh>Message</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Date">
<MudTooltip Text="@context.TimestampUtc.ToLocalTime().ToString("F")">
<MudText Typo="Typo.body2">@context.TimestampUtc.ToLocalTime().ToString("g")</MudText>
</MudTooltip>
</MudTd>
<MudTd DataLabel="Niveau">
<MudChip T="string" Size="Size.Small" Color="@GetLogLevelColor(context.Level)">
@context.Level
</MudChip>
</MudTd>
<MudTd DataLabel="Source">
<MudText Typo="Typo.body2" Color="Color.Secondary">@(context.Source ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="Message">
@if (!string.IsNullOrEmpty(context.Exception))
{
<MudTooltip Text="@context.Exception">
<MudText Typo="Typo.body2" Class="logs-message">@context.Message</MudText>
</MudTooltip>
}
else
{
<MudText Typo="Typo.body2" Class="logs-message">@context.Message</MudText>
}
</MudTd>
</RowTemplate>
<NoRecordsContent>
<MudPaper Class="pa-8 text-center" Style="border-radius: 12px;">
<MudIcon Icon="@Icons.Material.Filled.ReceiptLong" Size="Size.Large" Color="Color.Secondary" />
<MudText Typo="Typo.h6" Color="Color.Secondary" Class="mt-4">Aucun log</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary">
L'agent n'a rien remonté pour ces filtres.
</MudText>
</MudPaper>
</NoRecordsContent>
</MudTable>
<div class="d-flex align-center pa-4 mt-4" Style="border-radius: 8px;">
<MudText Typo="Typo.body2" Class="mr-4">
Page @_logPage sur @_logTotalPages (@_logTotal entrées)
</MudText>
<MudSpacer />
<MudButton Variant="Variant.Outlined" Size="Size.Small" Class="mr-2"
Disabled="@(_logPage <= 1)" OnClick="@(() => GoToLogPage(_logPage - 1))">
← Précédent
</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small"
Disabled="@(_logPage >= _logTotalPages)" OnClick="@(() => GoToLogPage(_logPage + 1))">
Suivant →
</MudButton>
</div>
}
</ChildContent>
<Actions>
<MudSwitch T="bool" Value="@_autoRefresh" ValueChanged="@ToggleAutoRefresh"
Color="Color.Primary" Class="mr-2" AdornmentLabel="Auto-refresh"
Label="Auto-refresh" />
<MudTooltip Text="Rafraîchir">
<MudIconButton Icon="@Icons.Material.Filled.Refresh" Size="Size.Small"
OnClick="@(() => LoadLogsAsync(keepPage: true))" aria-label="Actualiser les logs" />
</MudTooltip>
</Actions>
</SectionCard>
<div class="d-flex gap-4 mt-4">
<MudButton Variant="Variant.Outlined" Color="Color.Default"
OnClick="@(() => Nav.NavigateTo($"/sites/{_agent.SiteId}/agents"))">
← Agents du site
</MudButton>
<MudButton Variant="Variant.Text" Color="Color.Default"
OnClick="@(() => Nav.NavigateTo("/admin/agents"))">
← Tous les agents
</MudButton>
<MudSpacer />
<MudTooltip Text="Supprimer cet agent">
<MudButton Variant="Variant.Outlined" Color="Color.Error"
StartIcon="@Icons.Material.Filled.Delete"
OnClick="@(() => _confirmDeleteAgentVisible = true)">
Supprimer
</MudButton>
</MudTooltip>
</div>
}
@* ─── Delete Confirmation Dialog ─── *@
<MudDialog @bind-Visible="_confirmDeleteVisible" Options="_dialogOptions">
<TitleContent>
<MudText Typo="Typo.h6">
<MudIcon Icon="@Icons.Material.Filled.Warning" Color="Color.Warning" Class="mr-2" />
Confirmer la suppression
</MudText>
</TitleContent>
<DialogContent>
<MudText>Supprimer le réglage <strong>@_deletingKey</strong> pour cet agent ?</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-2">
L'agent sera notifié en temps réel via SignalR et utilisera la valeur globale par défaut.
</MudText>
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _confirmDeleteVisible = false)">Annuler</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Error"
OnClick="@ExecuteRemoveSettingAsync"
Loading="@_deleting"
Disabled="@_deleting">Supprimer</MudButton>
</DialogActions>
</MudDialog>
@* ─── Delete Agent Confirmation Dialog ─── *@
<MudDialog @bind-Visible="_confirmDeleteAgentVisible">
<TitleContent>
<MudText Typo="Typo.h6">
<MudIcon Icon="@Icons.Material.Filled.Warning" Color="Color.Warning" Class="mr-2" />
Confirmer la suppression
</MudText>
</TitleContent>
<DialogContent>
<MudText>Supprimer l'agent <strong>@_agent?.Name</strong> ?</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-2">
Les caméras associées seront désassignées mais pas supprimées.
</MudText>
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _confirmDeleteAgentVisible = false)">Annuler</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Error"
OnClick="@ExecuteDeleteAgentAsync" Loading="@_deletingAgent" Disabled="@_deletingAgent">
Supprimer
</MudButton>
</DialogActions>
</MudDialog>
@* ─── Add / Edit Dialog ─── *@
<MudDialog @bind-Visible="_showEditDialog" Options="_dialogOptions">
<TitleContent>
<MudText Typo="Typo.h6">@(_editingSetting is null ? "Ajouter un réglage" : "Modifier le réglage")</MudText>
</TitleContent>
<DialogContent>
<MudGrid>
<MudItem xs="12">
<MudTextField Label="Clé"
@bind-Value="_editKey"
Disabled="@(_editingSetting is not null)"
For="@(() => _editKey)"
Required="true"
HelperText="Ex: heartbeat.interval.seconds" />
</MudItem>
<MudItem xs="12">
<MudTextField Label="Valeur"
@bind-Value="_editValue"
For="@(() => _editValue)"
Required="true" />
</MudItem>
</MudGrid>
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _showEditDialog = false)">Annuler</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Primary"
OnClick="@SaveSettingAsync"
Disabled="@_saving"
Loading="@_saving">
@(_editingSetting is null ? "Ajouter" : "Enregistrer")
</MudButton>
</DialogActions>
</MudDialog>
@code {
[Parameter] public Guid Id { get; set; }
private AgentItem? _agent;
private bool _loading = true;
private List<AgentMetricHistoryPoint> _metricHistory = [];
private bool _metricHistoryLoading;
private bool _metricHistoryError;
private string _metricRange = "24h";
// Updates
private LatestReleaseInfo? _updateInfo;
// Settings
private List<AgentSettingItem> _settings = [];
private List<AppSettingItem> _globalSettings = [];
private bool _settingsLoading;
private bool _settingsError;
private bool _saving;
private AgentSettingItem? _editingSetting;
private string _editKey = string.Empty;
private string _editValue = string.Empty;
private bool _showEditDialog;
private bool _confirmDeleteVisible;
private string _deletingKey = string.Empty;
private bool _deleting;
// Delete agent
private bool _confirmDeleteAgentVisible;
private bool _deletingAgent;
// Logs
private IReadOnlyList<AgentLogItem>? _logs;
private bool _logsLoading;
private bool _logsError;
private int _logPage = 1;
private int _logTotalPages = 1;
private int _logTotal;
private string? _logLevel;
private string? _logSearch;
private bool _autoRefresh;
private CancellationTokenSource? _refreshCts;
private bool _disposed;
private readonly DialogOptions _dialogOptions = new()
{
MaxWidth = MaxWidth.Small,
FullWidth = true,
CloseButton = true
};
protected override async Task OnInitializedAsync()
{
try
{
_agent = await Api.GetAgentAsync(Id);
if (_agent is not null)
{
await LoadMetricHistoryAsync(_metricRange);
await LoadSettingsAsync();
await LoadLogsAsync(keepPage: false);
_ = LoadUpdateInfoAsync();
}
}
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
finally { _loading = false; }
}
private async Task LoadMetricHistoryAsync(string range)
{
_metricRange = range;
_metricHistoryLoading = true;
_metricHistoryError = false;
try
{
_metricHistory = await Api.GetAgentMetricHistoryAsync(Id, range) ?? [];
}
catch
{
_metricHistoryError = true;
_metricHistory = [];
}
finally { _metricHistoryLoading = false; }
}
private List<MetricChartPoint> MetricSeries(Func<AgentMetricHistoryPoint, double?> selector)
=> _metricHistory.Select(point => new MetricChartPoint(point.TimestampUtc, selector(point))).ToList();
private static double? MemoryUsedPercent(AgentMetricHistoryPoint point)
=> point.MemoryUsedBytes is { } used && point.MemoryTotalBytes is > 0
? Math.Clamp(100d * used / point.MemoryTotalBytes.Value, 0, 100)
: null;
private async Task LoadSettingsAsync()
{
_settingsError = false;
_settingsLoading = true;
try
{
_globalSettings = (await Api.GetSettingsAsync())
.Where(s => s.AgentScoped)
.OrderBy(s => s.Category)
.ThenBy(s => s.Key)
.ToList();
_settings = await Api.GetAgentSettingsAsync(Id);
}
catch
{
_settingsError = true;
_settings = [];
_globalSettings = [];
}
finally { _settingsLoading = false; }
}
private async Task LoadUpdateInfoAsync()
{
try { _updateInfo = await Api.GetLatestUpdateAsync(); }
catch { _updateInfo = null; }
await InvokeAsync(StateHasChanged);
}
private async Task TriggerUpdateAsync()
{
try
{
var result = await Api.TriggerAgentUpdateAsync(Id);
if (result is not null)
Snackbar.Add($"Mise à jour vers v{result.Version} déclenchée", Severity.Success);
else
Snackbar.Add("Erreur lors du déclenchement de la mise à jour", Severity.Error);
}
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
}
private async Task ExecuteDeleteAgentAsync()
{
_deletingAgent = true;
try
{
_confirmDeleteAgentVisible = false;
var error = await Api.DeleteAgentAsync(Id);
if (error is null)
{
Snackbar.Add($"Agent \"{_agent?.Name}\" supprimé", Severity.Success);
Nav.NavigateTo("/admin/agents");
}
else
{
Snackbar.Add(error, Severity.Error);
}
}
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
finally { _deletingAgent = false; }
}
/// <summary>Returns the effective value for a global setting key (override wins).</summary>
private string EffectiveValue(string key, string globalValue)
=> _settings.FirstOrDefault(s => s.Key == key)?.Value ?? globalValue;
/// <summary>True when the agent overrides this global key.</summary>
private bool IsOverridden(string key)
=> _settings.Any(s => s.Key == key);
private async Task SaveGlobalOverrideAsync(AppSettingItem setting, string value)
{
_saving = true;
try
{
var response = await Api.SetAgentSettingAsync(Id, new SetAgentSettingRequest(setting.Key, value));
if (response.IsSuccessStatusCode)
{
Snackbar.Add($"« {setting.Key} » surchargé pour cet agent — envoyé en temps réel", Severity.Success);
await LoadSettingsAsync();
}
else
{
var error = await response.Content.ReadAsStringAsync();
Snackbar.Add($"Erreur : {error}", Severity.Error);
}
}
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
finally { _saving = false; }
}
private async Task SaveGlobalOverrideBoolAsync(AppSettingItem setting, bool value)
=> await SaveGlobalOverrideAsync(setting, value.ToString().ToLowerInvariant());
private void OpenAddDialog()
{
_editingSetting = null;
_editKey = string.Empty;
_editValue = string.Empty;
_showEditDialog = true;
}
private void OpenEditDialog(AgentSettingItem setting)
{
_editingSetting = setting;
_editKey = setting.Key;
_editValue = setting.Value;
_showEditDialog = true;
}
private async Task SaveSettingAsync()
{
if (string.IsNullOrWhiteSpace(_editKey)) return;
_saving = true;
try
{
var request = new SetAgentSettingRequest(_editKey.Trim(), _editValue);
var response = await Api.SetAgentSettingAsync(Id, request);
if (response.IsSuccessStatusCode)
{
Snackbar.Add("Réglage enregistré et envoyé à l'agent en temps réel", Severity.Success);
_showEditDialog = false;
await LoadSettingsAsync();
}
else
{
var error = await response.Content.ReadAsStringAsync();
Snackbar.Add($"Erreur : {error}", Severity.Error);
}
}
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
finally { _saving = false; }
}
private void ConfirmRemoveSetting(AgentSettingItem setting)
{
_deletingKey = setting.Key;
_confirmDeleteVisible = true;
}
private async Task ExecuteRemoveSettingAsync()
{
_deleting = true;
try
{
var response = await Api.RemoveAgentSettingAsync(Id, _deletingKey);
if (response.IsSuccessStatusCode)
{
_confirmDeleteVisible = false;
Snackbar.Add("Réglage supprimé, agent notifié en temps réel", Severity.Success);
await LoadSettingsAsync();
}
else
{
Snackbar.Add("Erreur lors de la suppression", Severity.Error);
}
}
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
finally { _deleting = false; }
}
private async Task ExecuteRemoveSettingByKey(string key)
{
_deleting = true;
try
{
var response = await Api.RemoveAgentSettingAsync(Id, key);
if (response.IsSuccessStatusCode)
{
Snackbar.Add($"« {key} » réinitialisé à la valeur globale — agent notifié", Severity.Success);
await LoadSettingsAsync();
}
else
{
Snackbar.Add("Erreur lors de la réinitialisation", Severity.Error);
}
}
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
finally { _deleting = false; }
}
private async Task LoadLogsAsync(bool keepPage)
{
if (!keepPage) _logPage = 1;
_logsError = false;
_logsLoading = true;
try
{
var result = await Api.GetAgentLogsAsync(Id, _logLevel, _logSearch, _logPage);
if (result is not null)
{
_logs = result.Items;
_logTotal = result.TotalCount;
_logTotalPages = Math.Max(1, (int)Math.Ceiling(result.TotalCount / (double)result.PageSize));
}
}
catch
{
_logsError = true;
_logs = [];
}
finally
{
_logsLoading = false;
if (!_disposed) await InvokeAsync(StateHasChanged);
}
}
private async Task GoToLogPage(int page)
{
_logPage = page;
await LoadLogsAsync(keepPage: true);
}
private async Task ToggleAutoRefresh(bool enabled)
{
_autoRefresh = enabled;
if (_refreshCts is not null)
{
await _refreshCts.CancelAsync();
_refreshCts.Dispose();
_refreshCts = null;
}
if (enabled)
{
_refreshCts = new CancellationTokenSource();
_ = AutoRefreshLoopAsync(_refreshCts.Token);
}
}
private async Task AutoRefreshLoopAsync(CancellationToken ct)
{
try
{
while (!ct.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(10), ct);
if (!_disposed && _agent is not null)
await LoadLogsAsync(keepPage: true);
}
}
catch (OperationCanceledException) { /* arrêt volontaire */ }
}
private static Color GetLogLevelColor(string level) => level switch
{
"Critical" or "Error" => Color.Error,
"Warning" => Color.Warning,
"Information" => Color.Info,
_ => Color.Default
};
public async ValueTask DisposeAsync()
{
_disposed = true;
if (_refreshCts is not null)
{
await _refreshCts.CancelAsync();
_refreshCts.Dispose();
_refreshCts = null;
}
}
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" => "●",
"Offline" => "○",
"Error" => "⚠",
_ => "?"
};
private static string FormatMemory(long mb) => mb switch
{
> 102400 => $"{mb / 1024:F0} Go",
> 0 => $"{mb} Mo",
_ => "-"
};
// ─── Settings visual helpers ─────────────────────────────────────
private static Color GetAgentTypeColor(string valueType) => valueType.ToLowerInvariant() switch
{
"boolean" or "bool" => Color.Success,
"number" or "int" or "integer" or "double" => Color.Info,
"select" or "dropdown" => Color.Warning,
_ => Color.Secondary
};
private static string GetAgentTypeIcon(string valueType) => valueType.ToLowerInvariant() switch
{
"boolean" or "bool" => Icons.Material.Filled.ToggleOn,
"number" or "int" or "integer" or "double" => Icons.Material.Filled.Tag,
"select" or "dropdown" => Icons.Material.Filled.ArrowDropDownCircle,
_ => Icons.Material.Filled.TextFields
};
private static string GetAgentCategoryIcon(string category) => category.ToLowerInvariant() switch
{
"detection" => Icons.Material.Filled.Visibility,
"recording" => Icons.Material.Filled.Videocam,
"logging" or "log" => Icons.Material.Filled.BugReport,
"network" => Icons.Material.Filled.Wifi,
"storage" => Icons.Material.Filled.Storage,
"notification" or "notifications" => Icons.Material.Filled.Notifications,
"heartbeat" => Icons.Material.Filled.MonitorHeart,
_ => Icons.Material.Filled.Settings
};
private static string HumanizeAgentKey(string key)
{
var parts = key.Split('.', '_', '-');
return string.Join(' ', parts.Select(p => p.Length <= 2
? p.ToUpperInvariant()
: char.ToUpperInvariant(p[0]) + p[1..]));
}
// ─── Inventory helpers ─────────────────────────────────────────
private static string FormatBytes(long bytes) => bytes switch
{
>= 1_073_741_824L => $"{bytes / 1_073_741_824.0:F1} Go",
>= 1_048_576L => $"{bytes / 1_048_576.0:F1} Mo",
>= 1024L => $"{bytes / 1024.0:F1} Ko",
_ => $"{bytes} o"
};
private static string FormatUptime(long seconds) => seconds switch
{
>= 86400 => $"{seconds / 86400}j {seconds % 86400 / 3600}h",
>= 3600 => $"{seconds / 3600}h {seconds % 3600 / 60}m",
>= 60 => $"{seconds / 60}m {seconds % 60}s",
_ => $"{seconds}s"
};
private static List<DiskDto> ParseDiskJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<DiskDto>>(json) ?? [];
}
catch { return []; }
}
private static List<GpuDto> ParseGpuJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<GpuDto>>(json) ?? [];
}
catch { return []; }
}
private static List<NetworkDto> ParseNetworkJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<NetworkDto>>(json) ?? [];
}
catch { return []; }
}
private static List<TempDto> ParseTemperatureJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<TempDto>>(json) ?? [];
}
catch { return []; }
}
// DTOs for JSON deserialization
private sealed class DiskDto
{
public string MountPoint { get; init; } = "";
public string FileSystem { get; init; } = "";
public long? TotalBytes { get; init; } = null;
public long? UsedBytes { get; init; } = null;
public string Type { get; init; } = "Unknown";
}
[Serializable]
private sealed class GpuDto
{
[JsonPropertyName("model")]
public string? Model { get; init; }
[JsonPropertyName("vramBytes")]
public long? VramBytes { get; init; }
[JsonPropertyName("driverVersion")]
public string? DriverVersion { get; init; }
[JsonPropertyName("temperatureCelsius")]
public double? TemperatureCelsius { get; init; }
[JsonPropertyName("utilizationPercent")]
public double? UtilizationPercent { get; init; }
[JsonPropertyName("backend")]
public string? Backend { get; init; }
[JsonPropertyName("encoderSupport")]
public string? EncoderSupport { get; init; }
}
[Serializable]
private sealed class NetworkDto
{
public string Name { get; init; } = "";
[JsonPropertyName("ipAddress")]
public string? IpAddress { get; init; }
[JsonPropertyName("macAddress")]
public string? MacAddress { get; init; }
[JsonPropertyName("speedMbps")]
public long? SpeedMbps { get; init; }
}
[Serializable]
private sealed class TempDto
{
public string Zone { get; init; } = "";
[JsonPropertyName("temperatureCelsius")]
public double TemperatureCelsius { get; init; }
}
}