Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Successful in 19m19s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 6m13s
Heimdall Gitea / Build and scan agent image (push) Successful in 14m44s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m48s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m9s
Heimdall Gitea / CI policy (push) Successful in 10s
Merge pull request #138 Co-authored-by: Arnaud Dartois <admin@tordais.cc>
334 lines
16 KiB
C#
334 lines
16 KiB
C#
using System.Diagnostics;
|
|
using System.Globalization;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Heimdall.Agent.Services;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Heimdall.Agent;
|
|
|
|
/// <summary>
|
|
/// Starts an opt-in FFmpeg segment process for enabled cameras, persists completed
|
|
/// segments under the Agent state volume, and retries uploads until Central acknowledges them.
|
|
/// </summary>
|
|
public sealed class AgentRecordingService : BackgroundService
|
|
{
|
|
private const long MaxSegmentBytes = 100 * 1024 * 1024;
|
|
private static readonly TimeSpan LoopDelay = TimeSpan.FromSeconds(5);
|
|
private readonly CameraConfigStore _cameras;
|
|
private readonly CameraStreamService _streams;
|
|
private readonly AgentState _state;
|
|
private readonly AgentOptions _options;
|
|
private readonly IHttpClientFactory _clients;
|
|
private readonly ILogger<AgentRecordingService> _logger;
|
|
private readonly RecordingTriggerStore _triggers;
|
|
private readonly Dictionary<Guid, RecordingSession> _sessions = [];
|
|
private readonly SemaphoreSlim _lifecycle = new(1, 1);
|
|
private string _spoolRoot = string.Empty;
|
|
|
|
public AgentRecordingService(CameraConfigStore cameras, CameraStreamService streams, AgentState state,
|
|
IOptions<AgentOptions> options, IHttpClientFactory clients, ILogger<AgentRecordingService> logger,
|
|
RecordingTriggerStore? triggers = null)
|
|
{
|
|
_cameras = cameras;
|
|
_streams = streams;
|
|
_state = state;
|
|
_options = options.Value;
|
|
_clients = clients;
|
|
_logger = logger;
|
|
_triggers = triggers ?? new RecordingTriggerStore(options);
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
var stateDirectory = _options.StateDirectory ??
|
|
(OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
|
|
_spoolRoot = Path.GetFullPath(Path.Combine(stateDirectory, "recordings"));
|
|
Directory.CreateDirectory(_spoolRoot);
|
|
if (OperatingSystem.IsLinux())
|
|
File.SetUnixFileMode(_spoolRoot, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
|
|
|
try
|
|
{
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
try
|
|
{
|
|
await ReconcileAsync(stoppingToken).ConfigureAwait(false);
|
|
await UploadCompletedSegmentsAsync(stoppingToken).ConfigureAwait(false);
|
|
await TrimSpoolAsync(stoppingToken).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning("Recording loop failed (error type {ErrorType})", ex.GetType().Name);
|
|
}
|
|
await Task.Delay(LoopDelay, stoppingToken).ConfigureAwait(false);
|
|
}
|
|
}
|
|
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
|
|
finally
|
|
{
|
|
foreach (var cameraId in _sessions.Keys.ToArray())
|
|
await StopSessionAsync(cameraId, CancellationToken.None).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
private async Task ReconcileAsync(CancellationToken ct)
|
|
{
|
|
await _lifecycle.WaitAsync(ct).ConfigureAwait(false);
|
|
try
|
|
{
|
|
var configured = _cameras.Cameras.ToDictionary(c => c.CameraId);
|
|
await _triggers.ClearExceptAsync(configured.Values
|
|
.Where(camera => camera.Enabled && camera.EventRecordingEnabled)
|
|
.Select(camera => camera.CameraId).ToHashSet(), ct).ConfigureAwait(false);
|
|
foreach (var (cameraId, session) in _sessions.ToArray())
|
|
{
|
|
if (!configured.TryGetValue(cameraId, out var camera) || !camera.Enabled ||
|
|
camera.RtspUrl != session.RtspUrl || !_streams.IsStreamActive(cameraId) || session.Process.HasExited)
|
|
{
|
|
await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false);
|
|
continue;
|
|
}
|
|
if (!camera.RecordingEnabled && !(camera.EventRecordingEnabled &&
|
|
(await _triggers.GetStatusAsync(cameraId, ct).ConfigureAwait(false)).IsActive))
|
|
await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
foreach (var camera in configured.Values.Where(c => c.Enabled &&
|
|
(c.RecordingEnabled || c.EventRecordingEnabled) &&
|
|
!string.IsNullOrWhiteSpace(c.RtspUrl)))
|
|
{
|
|
var triggerStatus = camera.EventRecordingEnabled
|
|
? await _triggers.GetStatusAsync(camera.CameraId, ct).ConfigureAwait(false)
|
|
: RecordingTriggerStore.RecordingTriggerStatus.Inactive;
|
|
var shouldRecord = camera.RecordingEnabled || triggerStatus.IsActive;
|
|
if (shouldRecord && _streams.IsStreamActive(camera.CameraId) && !_sessions.ContainsKey(camera.CameraId))
|
|
StartSession(camera, camera.RecordingEnabled ? null : triggerStatus.FirstTriggeredAtUtc);
|
|
}
|
|
}
|
|
finally { _lifecycle.Release(); }
|
|
}
|
|
|
|
private void StartSession(AgentCameraConfig camera, DateTime? triggeredAtUtc)
|
|
{
|
|
var cameraRoot = Path.Combine(_spoolRoot, camera.CameraId.ToString("N"));
|
|
var sessionDirectory = Path.Combine(cameraRoot, Guid.NewGuid().ToString("N"));
|
|
Directory.CreateDirectory(sessionDirectory);
|
|
if (OperatingSystem.IsLinux())
|
|
File.SetUnixFileMode(sessionDirectory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
|
var startedAt = triggeredAtUtc ?? DateTime.UtcNow;
|
|
File.WriteAllText(Path.Combine(sessionDirectory, "started-at.txt"), startedAt.ToString("O", CultureInfo.InvariantCulture));
|
|
var startInfo = CreateStartInfo(_options.RecordingFfmpegPath, camera.RtspUrl!, sessionDirectory,
|
|
_options.RecordingSegmentSeconds);
|
|
Process? process = null;
|
|
try
|
|
{
|
|
process = new Process { StartInfo = startInfo, EnableRaisingEvents = true };
|
|
if (!process.Start()) throw new InvalidOperationException("FFmpeg did not start");
|
|
var session = new RecordingSession(camera.CameraId, camera.RtspUrl!, sessionDirectory, startedAt, process);
|
|
_sessions[camera.CameraId] = session;
|
|
session.ErrorDrain = DrainStandardErrorAsync(process);
|
|
_logger.LogInformation("Video recording started for camera {CameraId}", camera.CameraId);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
process?.Dispose();
|
|
_logger.LogWarning("Video recording could not start for camera {CameraId} (error type {ErrorType})",
|
|
camera.CameraId, ex.GetType().Name);
|
|
}
|
|
}
|
|
|
|
internal static ProcessStartInfo CreateStartInfo(string ffmpegPath, string rtspUrl, string sessionDirectory,
|
|
int segmentSeconds)
|
|
{
|
|
var info = new ProcessStartInfo
|
|
{
|
|
FileName = ffmpegPath,
|
|
RedirectStandardInput = true,
|
|
RedirectStandardError = true,
|
|
UseShellExecute = false,
|
|
CreateNoWindow = true,
|
|
};
|
|
foreach (var argument in new[]
|
|
{
|
|
"-hide_banner", "-loglevel", "error", "-rtsp_transport", "tcp", "-i", rtspUrl,
|
|
"-map", "0:v:0", "-map", "0:a:0?", "-c:v", "copy", "-c:a", "aac", "-b:a", "128k",
|
|
"-f", "segment", "-segment_time",
|
|
segmentSeconds.ToString(CultureInfo.InvariantCulture), "-segment_format", "mp4",
|
|
"-reset_timestamps", "1", "-segment_list", Path.Combine(sessionDirectory, "segments.csv"),
|
|
"-segment_list_type", "csv", "-segment_list_size", "10000",
|
|
Path.Combine(sessionDirectory, "segment-%06d.mp4")
|
|
}) info.ArgumentList.Add(argument);
|
|
return info;
|
|
}
|
|
|
|
private static async Task DrainStandardErrorAsync(Process process)
|
|
{
|
|
try
|
|
{
|
|
while (await process.StandardError.ReadLineAsync().ConfigureAwait(false) is not null) { }
|
|
}
|
|
catch (IOException) { }
|
|
catch (ObjectDisposedException) { }
|
|
}
|
|
|
|
private async Task StopSessionAsync(Guid cameraId, CancellationToken ct)
|
|
{
|
|
await _lifecycle.WaitAsync(ct).ConfigureAwait(false);
|
|
try
|
|
{
|
|
if (_sessions.TryGetValue(cameraId, out var session))
|
|
await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false);
|
|
}
|
|
finally { _lifecycle.Release(); }
|
|
}
|
|
|
|
private async Task StopSessionCoreAsync(Guid cameraId, RecordingSession session, CancellationToken ct)
|
|
{
|
|
_sessions.Remove(cameraId);
|
|
try
|
|
{
|
|
if (!session.Process.HasExited)
|
|
{
|
|
try { await session.Process.StandardInput.WriteLineAsync("q").ConfigureAwait(false); }
|
|
catch (IOException) { }
|
|
try { await session.Process.WaitForExitAsync(ct).WaitAsync(TimeSpan.FromSeconds(5), ct).ConfigureAwait(false); }
|
|
catch (TimeoutException) { session.Process.Kill(entireProcessTree: true); }
|
|
catch (InvalidOperationException) { }
|
|
}
|
|
if (session.ErrorDrain is not null) await session.ErrorDrain.ConfigureAwait(false);
|
|
_logger.LogInformation("Video recording stopped for camera {CameraId}", cameraId);
|
|
}
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogDebug("FFmpeg cleanup failed for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name);
|
|
}
|
|
finally { session.Process.Dispose(); }
|
|
}
|
|
|
|
private async Task UploadCompletedSegmentsAsync(CancellationToken ct)
|
|
{
|
|
if (!Directory.Exists(_spoolRoot)) return;
|
|
foreach (var manifest in Directory.EnumerateFiles(_spoolRoot, "segments.csv", SearchOption.AllDirectories))
|
|
{
|
|
ct.ThrowIfCancellationRequested();
|
|
if (!Guid.TryParseExact(Directory.GetParent(Directory.GetParent(manifest)!.FullName)!.Name, "N", out var cameraId))
|
|
continue;
|
|
DateTime startedAt;
|
|
try
|
|
{
|
|
startedAt = DateTime.Parse(File.ReadAllText(Path.Combine(Path.GetDirectoryName(manifest)!, "started-at.txt")),
|
|
CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind).ToUniversalTime();
|
|
}
|
|
catch (IOException) { continue; }
|
|
catch (FormatException) { continue; }
|
|
string[] rows;
|
|
try { rows = await File.ReadAllLinesAsync(manifest, ct).ConfigureAwait(false); }
|
|
catch (IOException) { continue; }
|
|
foreach (var row in rows)
|
|
{
|
|
var fields = row.Split(',');
|
|
if (fields.Length < 3) continue;
|
|
var fileName = Path.GetFileName(fields[0]);
|
|
if (!fileName.StartsWith("segment-", StringComparison.Ordinal) || !fileName.EndsWith(".mp4", StringComparison.Ordinal) ||
|
|
!double.TryParse(fields[1], CultureInfo.InvariantCulture, out var startSeconds) ||
|
|
!double.TryParse(fields[2], CultureInfo.InvariantCulture, out var endSeconds)) continue;
|
|
var duration = endSeconds - startSeconds;
|
|
if (duration is < 1 or > 300 || !double.IsFinite(duration) || !double.IsFinite(startSeconds)) continue;
|
|
var path = Path.Combine(Path.GetDirectoryName(manifest)!, fileName);
|
|
if (!File.Exists(path)) continue;
|
|
var info = new FileInfo(path);
|
|
if (info.Length > MaxSegmentBytes)
|
|
{
|
|
_logger.LogWarning("Dropping oversized video segment for camera {CameraId} ({SizeBytes} bytes)", cameraId, info.Length);
|
|
info.Delete();
|
|
continue;
|
|
}
|
|
await UploadSegmentAsync(cameraId, path, startedAt.AddSeconds(startSeconds), duration, ct).ConfigureAwait(false);
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task UploadSegmentAsync(Guid cameraId, string path, DateTime timestamp, double duration, CancellationToken ct)
|
|
{
|
|
var relativePath = Path.GetRelativePath(_spoolRoot, path).Replace(Path.DirectorySeparatorChar, '/');
|
|
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(relativePath));
|
|
var recordingId = new Guid(hash.AsSpan(0, 16));
|
|
var url = $"api/cameras/{cameraId:D}/recordings/{recordingId:D}/content?timestamp={Uri.EscapeDataString(timestamp.ToString("O", CultureInfo.InvariantCulture))}&durationSeconds={duration.ToString(CultureInfo.InvariantCulture)}";
|
|
try
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Put, url);
|
|
request.Headers.Add("X-API-Key", _state.ApiKey);
|
|
await using var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
|
|
128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
|
request.Content = new StreamContent(input);
|
|
request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4");
|
|
request.Content.Headers.ContentLength = input.Length;
|
|
using var response = await _clients.CreateClient("Central").SendAsync(request,
|
|
HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
_logger.LogWarning("Video segment upload returned HTTP {StatusCode} for camera {CameraId}",
|
|
(int)response.StatusCode, cameraId);
|
|
return;
|
|
}
|
|
input.Close();
|
|
File.Delete(path);
|
|
}
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
|
|
catch (HttpRequestException ex)
|
|
{
|
|
_logger.LogWarning("Video segment upload failed for camera {CameraId} (error type {ErrorType})",
|
|
cameraId, ex.GetType().Name);
|
|
}
|
|
catch (IOException ex)
|
|
{
|
|
_logger.LogWarning("Video segment could not be read or removed for camera {CameraId} (error type {ErrorType})",
|
|
cameraId, ex.GetType().Name);
|
|
}
|
|
}
|
|
|
|
private async Task TrimSpoolAsync(CancellationToken ct)
|
|
{
|
|
var ready = new List<FileInfo>();
|
|
foreach (var manifest in Directory.EnumerateFiles(_spoolRoot, "segments.csv", SearchOption.AllDirectories))
|
|
{
|
|
string[] rows;
|
|
try { rows = await File.ReadAllLinesAsync(manifest, ct).ConfigureAwait(false); }
|
|
catch (IOException) { continue; }
|
|
foreach (var row in rows)
|
|
{
|
|
var fileName = Path.GetFileName(row.Split(',')[0]);
|
|
if (!fileName.StartsWith("segment-", StringComparison.Ordinal) || !fileName.EndsWith(".mp4", StringComparison.Ordinal)) continue;
|
|
var path = Path.Combine(Path.GetDirectoryName(manifest)!, fileName);
|
|
if (File.Exists(path)) ready.Add(new FileInfo(path));
|
|
}
|
|
}
|
|
var total = ready.Sum(file => file.Length);
|
|
foreach (var file in ready.OrderBy(file => file.LastWriteTimeUtc))
|
|
{
|
|
if (total <= _options.RecordingSpoolMaxBytes) break;
|
|
ct.ThrowIfCancellationRequested();
|
|
var size = file.Length;
|
|
try
|
|
{
|
|
file.Delete();
|
|
total -= size;
|
|
_logger.LogWarning("Dropping oldest queued video segment for camera {CameraId}; local recording spool reached its configured limit",
|
|
Path.GetFileName(Path.GetDirectoryName(Path.GetDirectoryName(file.FullName))));
|
|
}
|
|
catch (IOException) { }
|
|
catch (UnauthorizedAccessException) { }
|
|
}
|
|
}
|
|
|
|
private sealed record RecordingSession(Guid CameraId, string RtspUrl, string Directory,
|
|
DateTime StartedAt, Process Process)
|
|
{
|
|
public Task? ErrorDrain { get; set; }
|
|
}
|
|
}
|