Heimdall Gitea / Build and tests (pull_request) Canceled after 0s
Heimdall Gitea / Build and scan server image (pull_request) Canceled after 0s
Heimdall Gitea / Build and scan agent image (pull_request) Canceled after 0s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Canceled after 0s
Heimdall Gitea / Publish versioned release (pull_request) Canceled after 0s
98 lines
3.8 KiB
C#
98 lines
3.8 KiB
C#
using Heimdall.Application.Services;
|
|
using Heimdall.Domain.Enums;
|
|
using Heimdall.Infrastructure.Data;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Heimdall.Infrastructure.Jobs;
|
|
|
|
/// <summary>
|
|
/// Hangfire recurring job that detects stale or offline agents and automatically
|
|
/// reassigns their cameras to online agents in the same site.
|
|
/// Runs every 60 seconds.
|
|
/// </summary>
|
|
public sealed class AgentFailoverJob
|
|
{
|
|
private readonly IDbContextFactory<AppDbContext> _dbFactory;
|
|
private readonly ICameraAssignmentService _assignmentService;
|
|
private readonly ILogger<AgentFailoverJob> _logger;
|
|
|
|
public AgentFailoverJob(
|
|
IDbContextFactory<AppDbContext> dbFactory,
|
|
ICameraAssignmentService assignmentService,
|
|
ILogger<AgentFailoverJob> logger)
|
|
{
|
|
_dbFactory = dbFactory;
|
|
_assignmentService = assignmentService;
|
|
_logger = logger;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Check online agents for stale heartbeats and retry camera failover for
|
|
/// offline agents that still own enabled cameras.
|
|
/// </summary>
|
|
public async Task ExecuteAsync(CancellationToken ct = default)
|
|
{
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
|
var now = DateTime.UtcNow;
|
|
var maximumStaleAt = now.AddSeconds(-HeartbeatTimeoutPolicy.MaximumTimeoutSeconds);
|
|
var timeoutPolicy = await HeartbeatTimeoutPolicy.LoadAsync(db, ct).ConfigureAwait(false);
|
|
|
|
var staleAgents = await db.Agents
|
|
.AsTracking()
|
|
.Where(a => !a.IsDeleted &&
|
|
((a.Status == AgentStatus.Online
|
|
&& a.LastHeartbeat != null
|
|
&& a.LastHeartbeat < maximumStaleAt)
|
|
|| (a.Status == AgentStatus.Offline
|
|
&& a.Cameras.Any(camera => !camera.IsDeleted && camera.Status != CameraStatus.Disabled))))
|
|
.ToListAsync(ct);
|
|
|
|
staleAgents = staleAgents
|
|
.Where(agent => agent.Status != AgentStatus.Online ||
|
|
agent.LastHeartbeat < now.AddSeconds(-timeoutPolicy.GetTimeoutSeconds(agent.Id)))
|
|
.ToList();
|
|
|
|
foreach (var agent in staleAgents)
|
|
{
|
|
_logger.LogWarning(
|
|
"Agent {AgentId} ({Name}) is offline or heartbeat stale — last was {LastHeartbeat}. Triggering failover.",
|
|
agent.Id, agent.Name, agent.LastHeartbeat);
|
|
|
|
agent.MarkOffline();
|
|
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
|
|
|
try
|
|
{
|
|
var result = await _assignmentService.FailoverAgentAsync(agent.Id, ct).ConfigureAwait(false);
|
|
if (result.IsSuccess && result.Data?.Count > 0)
|
|
{
|
|
_logger.LogWarning(
|
|
"Failover complete for agent {AgentId}: {Count} cameras reassigned",
|
|
agent.Id, result.Data.Count);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Failover failed for agent {AgentId}", agent.Id);
|
|
}
|
|
}
|
|
|
|
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
|
|
|
// Reconcile waiting cameras on every sweep, including after an agent reconnects.
|
|
var waitingSites = await db.Cameras.AsNoTracking()
|
|
.Where(c => !c.IsDeleted && c.Status != CameraStatus.Disabled && c.AgentId == null)
|
|
.Select(c => c.SiteId).Distinct().ToListAsync(ct);
|
|
foreach (var siteId in waitingSites)
|
|
await _assignmentService.AssignSiteCamerasAsync(siteId, AssignmentStrategy.Failover, ct);
|
|
|
|
if (staleAgents.Count > 0)
|
|
{
|
|
_logger.LogInformation(
|
|
"Failover sweep complete: {Count} agents marked offline",
|
|
staleAgents.Count);
|
|
}
|
|
}
|
|
}
|