Files
Heimdall/src/Heimdall.Application/Discovery/CameraStreamTemplates.cs
T
Arnaud Dartois 4792b69e46 feat(agent): télémétrie inventaire matériel — CPU/mémoire/disque/GPU/OS/réseau (Fixes #82 #83 #84 #85) (#137)
## Contexte

Implémentation des tickets #82, #83, #84, #85 — télémétrie inventaire matériel agent. L'objectif est de fournir au central un maximum d'informations sur les machines des agents (CPU, mémoire, disques, GPU, OS, réseau, conteneur) sans SSH.

## Changements

### Nouveaux collecteurs (src/Heimdall.Agent/Services/)
- **CpuInfoProvider** : parse `/proc/cpuinfo` (vendor, modèle, cœurs physiques/logiques, fréquence, flags AVX/AVX2/FMA/AVX512, cache), topologie, détection cgroup CPU (`/sys/fs/cgroup/cpu.max` v2)
- **DiskInventoryProvider** : énumère les montages (`/proc/mounts`), capacité/libre/type SSD/HDD via `/sys/block/*/queue/rotation`
- **GpuInventoryProvider** : nvidia-smi, sysfs DRM, vainfo, rocm-smi avec fallback silencieux, multi-GPU
- **HostInfoProvider** : os-release, uname, `/proc/uptime` (uptime machine ≠ process), températures sysfs
- **ContainerInfoProvider** : détection Docker (/.dockerenv, cgroup), ID conteneur, limites CPU/mémoire

### Refonte SystemMetricsProvider
- Séparation host vs process (RAM machine ≠ RAM conteneur ≠ WorkingSet64)
- Uptime machine (`/proc/uptime`) distinct de l'uptime process
- Mémoire swap

### Entité Agent + Migration
- Champs structurés CPU/mémoire/disque/GPU/OS/réseau (tous nullable, rétrocompatible)
- Migration EF `AddAgentTelemetryInventory`

### Transport heartbeat
- Inventaire au register + refresh périodique (5 min, pas à chaque tick)
- Champs JSON pour listes (disques, GPU, interfaces réseau, températures)

### UI Admin (AgentDetail.razor)
- Sections CPU, Mémoire/Disques, GPU, Machine/Conteneur avec barres de progression et badges

### Tests
- 40+ tests unitaires : providers, handlers, entité Agent
- Total : 999 tests verts (Domain 149, Application 397, Agent 210, Web 243)

## Tickets liés
- Fixes #82 — CPU inventory
- Fixes #83 — Mémoire & disque
- Fixes #84 — GPU inventory
- Fixes #85 — OS, conteneur, réseau

## Résultats des tests
- `dotnet build` : 0 erreur, 0 warning
- Domain.Tests : 149 passed
- Application.Tests : 397 passed
- Agent.Tests : 210 passed
- Web.Tests : 243 passed
- Total : 999 tests ✅

## Checklist
- [x] `dotnet build` vert (TreatWarningsAsErrors)
- [x] Tests unitaires verts
- [x] Migration EF créée
- [x] Champs nullable (rétrocompatible)
- [x] Pas de référence Infrastructure dans les contrôleurs
- [x] Collecteurs avec fallback silencieux (pas de crash sans GPU/Docker/sysfs)

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/137
2026-08-20 14:13:06 +02:00

152 lines
7.3 KiB
C#

using System.Globalization;
namespace Heimdall.Application.Discovery;
/// <summary>
/// Shared camera stream URL templates used by BOTH the Central (to build
/// candidate URLs for a discovery result) and the Agent (to build + test the
/// URLs on the camera LAN, since only the agent can reach the cameras).
/// Placeholders: {IP}, {PORT}, {CHANNEL}, {USERNAME}, {PASSWORD}.
/// Each template declares the protocol default port; <see cref="BuildUrls"/>
/// applies a per-protocol port filter so URLs only carry plausible ports
/// (open ports, or the protocol default as a fallback).
/// </summary>
public static class CameraStreamTemplates
{
/// <summary>URL templates for stream building. {IP}, {PORT}, {CHANNEL}, {USERNAME}, {PASSWORD}.</summary>
public static readonly Dictionary<string, string[]> StreamTemplates = new()
{
["p:onvif"] = ["rtsp://{IP}:{PORT}/onvif/media?profile=1"],
["p:rtsp-h264"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/stream1",
"rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/Streaming/Channels/{CHANNEL}01"],
["p:rtsp-h265"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/stream2",
"rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/Streaming/Channels/{CHANNEL}02"],
["p:mjpeg"] = ["http://{IP}:{PORT}/mjpeg", "http://{IP}:{PORT}/video.mjpg"],
["p:dvrrip"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/cam/realmonitor?channel={CHANNEL}&subtype=0",
"dvrip://{USERNAME}:{PASSWORD}@{IP}:{PORT}?channel={CHANNEL}&subtype=0"],
["p:rtmp"] = ["rtmp://{IP}:{PORT}/live/{CHANNEL}"],
["b:hikvision"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/Streaming/Channels/{CHANNEL}01",
"rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/Streaming/Channels/{CHANNEL}02"],
["b:dahua"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/cam/realmonitor?channel={CHANNEL}&subtype=0",
"dvrip://{USERNAME}:{PASSWORD}@{IP}:{PORT}?channel={CHANNEL}&subtype=0"],
// Imou (Dahua consumer brand): Dahua-style RTSP + HTTP snapshot/MJPEG CGI
["b:imou"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/cam/realmonitor?channel={CHANNEL}&subtype=0",
"http://{IP}:{PORT}/video.mjpg?oids=1&username={USERNAME}&password={PASSWORD}",
"http://{IP}:{PORT}/cgi-bin/snapshot.cgi?loginuse={USERNAME}&loginpas={PASSWORD}"],
["b:axis"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/axis-media/media.amp",
"http://{IP}:{PORT}/axis-cgi/mjpg/video.cgi"],
["b:vivotek"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/live.sdp"],
["b:amcrest"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/cam/realmonitor?channel={CHANNEL}&subtype=0"],
// Uniview / Bubble protocol (Uniview IPC/NVR expose bubble:// on port 80)
["b:uniview"] = ["bubble://{USERNAME}:{PASSWORD}@{IP}:{PORT}/bubble/live?ch={CHANNEL}&stream=0",
"rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/unicast/c{CHANNEL}/s0/live"],
// Reolink: ONVIF + RTSP (port 554) — very common on the LAN
["b:reolink"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/h264Preview_01_main",
"rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/h264Preview_01_sub"],
};
/// <summary>Protocol default ports — the fallback port used for an URL when no open port matches.</summary>
public static readonly Dictionary<string, int> ProtocolDefaultPorts = new(StringComparer.OrdinalIgnoreCase)
{
["rtsp"] = 554,
["rtsps"] = 554,
["rtmp"] = 1935,
["rtmps"] = 1935,
["http"] = 80,
["https"] = 443,
["bubble"] = 80,
["dvrip"] = 34567,
};
/// <summary>
/// True when a port is plausible for a stream protocol. Used by the
/// port filter: candidate URLs only carry ports that are either open on
/// the device or the protocol default.
/// </summary>
public static bool IsPortCompatible(string scheme, int port)
{
if (ProtocolDefaultPorts.TryGetValue(scheme, out var def) && port == def)
return true;
return scheme.ToLowerInvariant() switch
{
"rtsp" or "rtsps" => port is 554 or 8554 or 10554 or 5544 or 7070 or 7447 or 8000 or 8001 or 8080 or 8081 or 8090 or 81 or 88,
"rtmp" or "rtmps" => port == 1935,
"http" or "https" => port is 80 or 81 or 88 or 8080 or 8081 or 8090 or 8000 or 8001 or 443,
"bubble" => port is 80 or 8080,
"dvrip" => port is 34567 or 34568 or 37777,
_ => false,
};
}
/// <summary>
/// Build candidate stream URLs for a set of template ids. Falls back to a
/// generic RTSP URL when no template matches.
/// </summary>
/// <remarks>
/// Port selection per URL: when <paramref name="portFilter"/> is provided,
/// the protocol default port is used when present in the filter; otherwise
/// the first compatible open ports (max 2 per template) are used. URLs whose
/// protocol has no compatible open port are skipped. When no filter is
/// provided the protocol default port is used.
/// </remarks>
public static List<string> BuildUrls(
string[] ids, string ip, string? username, string? password, int channel = 0, int[]? portFilter = null)
{
var urls = new List<string>();
var filter = portFilter is { Length: > 0 }
? portFilter.Distinct().Order().ToArray()
: null;
foreach (var id in ids)
{
if (!StreamTemplates.TryGetValue(id, out var templates))
continue;
foreach (var template in templates)
{
var scheme = template[..template.IndexOf("://", StringComparison.Ordinal)].ToLowerInvariant();
var defaultPort = ProtocolDefaultPorts.TryGetValue(scheme, out var dp) ? dp : 554;
int[] ports;
if (filter is null)
{
ports = [defaultPort];
}
else
{
// Prefer the protocol default when open, else compatible open ports.
var compatible = filter.Where(p => IsPortCompatible(scheme, p)).ToArray();
if (compatible.Contains(defaultPort))
ports = [defaultPort];
else if (compatible.Length > 0)
ports = compatible.Take(2).ToArray();
else
continue; // no plausible port for this protocol → skip URL
}
foreach (var port in ports)
{
var url = template
.Replace("{IP}", ip)
.Replace("{PORT}", port.ToString(CultureInfo.InvariantCulture))
.Replace("{CHANNEL}", channel.ToString(CultureInfo.InvariantCulture))
.Replace("{USERNAME}", username ?? "admin")
.Replace("{PASSWORD}", password ?? "");
if (!urls.Contains(url))
urls.Add(url);
}
}
}
if (urls.Count == 0)
{
const int fallbackPort = 554;
urls.Add($"rtsp://{ip}:{fallbackPort}/stream1");
}
return urls;
}
}