fix(agent): align failover with heartbeat intervals
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
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
This commit is contained in:
1 parent
83ee648c2d
commit
8d5447f826
10 files changed
+125
-23
No files matched your search
@@ -19,6 +19,10 @@ public class SetAgentSettingCommandHandler : IRequestHandler<SetAgentSettingComm
|
||||
{
|
||||
var key = request.Key.Trim().ToLowerInvariant();
|
||||
|
||||
if (key == "heartbeat.interval.seconds" &&
|
||||
(!int.TryParse(request.Value, out var heartbeatInterval) || heartbeatInterval is < 5 or > 300))
|
||||
return ServiceResult<AgentSettingDto>.Failure("Heartbeat interval must be between 5 and 300 seconds", 400);
|
||||
|
||||
if (!await _db.AppSettings.AnyAsync(s => s.Key == key && s.AgentScoped, ct))
|
||||
return ServiceResult<AgentSettingDto>.Failure("Setting is not agent-scoped", 400);
|
||||
|
||||
|
||||
@@ -23,6 +23,10 @@ public class UpdateAppSettingCommandHandler : IRequestHandler<UpdateAppSettingCo
|
||||
|
||||
public async Task<ServiceResult<AppSettingDto>> Handle(UpdateAppSettingCommand request, CancellationToken ct)
|
||||
{
|
||||
if (request.Key.Trim().Equals("heartbeat.interval.seconds", StringComparison.OrdinalIgnoreCase) &&
|
||||
(!int.TryParse(request.Value, out var heartbeatInterval) || heartbeatInterval is < 5 or > 300))
|
||||
return ServiceResult<AppSettingDto>.Failure("Heartbeat interval must be between 5 and 300 seconds", 400);
|
||||
|
||||
var setting = await _db.AppSettings.FirstOrDefaultAsync(s => s.Key == request.Key, ct).ConfigureAwait(false);
|
||||
if (setting is null)
|
||||
return ServiceResult<AppSettingDto>.NotFound($"Setting '{request.Key}' not found");
|
||||
|
||||
@@ -9,5 +9,8 @@ public class SetAgentSettingValidator : AbstractValidator<SetAgentSettingRequest
|
||||
{
|
||||
RuleFor(x => x.Key).NotEmpty().MaximumLength(200);
|
||||
RuleFor(x => x.Value).NotNull();
|
||||
When(x => string.Equals(x.Key, "heartbeat.interval.seconds", StringComparison.OrdinalIgnoreCase), () =>
|
||||
RuleFor(x => x.Value).Must(value => int.TryParse(value, out var seconds) && seconds is >= 5 and <= 300)
|
||||
.WithMessage("Heartbeat interval must be between 5 and 300 seconds"));
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,9 @@ public static class JobSetup
|
||||
{
|
||||
public static void ConfigureRecurringJobs(IRecurringJobManager manager)
|
||||
{
|
||||
manager.AddOrUpdate<HeartbeatMonitorJob>(
|
||||
"heartbeat-monitor",
|
||||
job => job.ExecuteAsync(CancellationToken.None),
|
||||
"*/1 * * * *");
|
||||
// AgentFailoverJob owns the stale -> offline transition so it can
|
||||
// reassign cameras in the same pass. Remove the legacy competing job.
|
||||
manager.RemoveIfExists("heartbeat-monitor");
|
||||
|
||||
manager.AddOrUpdate<AgentFailoverJob>(
|
||||
"agent-failover",
|
||||
|
||||
@@ -7,8 +7,8 @@ using Microsoft.Extensions.Logging;
|
||||
namespace Heimdall.Infrastructure.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Hangfire recurring job that detects agents whose heartbeat is stale
|
||||
/// and automatically reassigns their cameras to online agents in the same site.
|
||||
/// 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
|
||||
@@ -17,9 +17,6 @@ public sealed class AgentFailoverJob
|
||||
private readonly ICameraAssignmentService _assignmentService;
|
||||
private readonly ILogger<AgentFailoverJob> _logger;
|
||||
|
||||
// Agents are marked offline after 90 seconds without heartbeat
|
||||
private static readonly TimeSpan OfflineThreshold = TimeSpan.FromSeconds(90);
|
||||
|
||||
public AgentFailoverJob(
|
||||
IDbContextFactory<AppDbContext> dbFactory,
|
||||
ICameraAssignmentService assignmentService,
|
||||
@@ -31,25 +28,35 @@ public sealed class AgentFailoverJob
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check all online agents. If any has a stale heartbeat while the system
|
||||
/// still shows it as Online, trigger failover.
|
||||
/// 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.Status == AgentStatus.Online
|
||||
&& a.LastHeartbeat != null
|
||||
&& a.LastHeartbeat < DateTime.UtcNow - OfflineThreshold
|
||||
&& !a.IsDeleted)
|
||||
.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}) heartbeat stale — last was {LastHeartbeat}. Triggering failover.",
|
||||
"Agent {AgentId} ({Name}) is offline or heartbeat stale — last was {LastHeartbeat}. Triggering failover.",
|
||||
agent.Id, agent.Name, agent.LastHeartbeat);
|
||||
|
||||
agent.MarkOffline();
|
||||
|
||||
@@ -6,7 +6,7 @@ using Microsoft.Extensions.Logging;
|
||||
namespace Heimdall.Infrastructure.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Marks agents as Offline if no heartbeat received for 90+ seconds.
|
||||
/// Marks agents Offline when their configured heartbeat cadence is exceeded.
|
||||
/// Runs every minute via Hangfire recurring job.
|
||||
/// Uses IDbContextFactory to avoid sharing a DbContext across Hangfire worker threads.
|
||||
/// </summary>
|
||||
@@ -25,18 +25,25 @@ public class HeartbeatMonitorJob
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
|
||||
var timeoutThreshold = DateTime.UtcNow.AddSeconds(-90);
|
||||
var now = DateTime.UtcNow;
|
||||
var maximumStaleAt = now.AddSeconds(-HeartbeatTimeoutPolicy.MaximumTimeoutSeconds);
|
||||
var timeoutPolicy = await HeartbeatTimeoutPolicy.LoadAsync(db, ct).ConfigureAwait(false);
|
||||
|
||||
var staleAgents = await db.Agents
|
||||
.Where(a => a.Status == AgentStatus.Online
|
||||
&& !a.IsDeleted
|
||||
&& a.LastHeartbeat != null
|
||||
&& a.LastHeartbeat < timeoutThreshold)
|
||||
&& a.LastHeartbeat < maximumStaleAt)
|
||||
.ToListAsync(ct);
|
||||
|
||||
staleAgents = staleAgents
|
||||
.Where(agent => agent.LastHeartbeat < now.AddSeconds(-timeoutPolicy.GetTimeoutSeconds(agent.Id)))
|
||||
.ToList();
|
||||
|
||||
if (staleAgents.Count == 0)
|
||||
return;
|
||||
|
||||
_logger.LogWarning("Marking {Count} agents as Offline (no heartbeat > 90s)", staleAgents.Count);
|
||||
_logger.LogWarning("Marking {Count} agents as Offline after their configured heartbeat timeout", staleAgents.Count);
|
||||
|
||||
foreach (var agent in staleAgents)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Infrastructure.Jobs;
|
||||
|
||||
/// <summary>Resolves the heartbeat cadence configured globally or for one agent.</summary>
|
||||
internal sealed class HeartbeatTimeoutPolicy
|
||||
{
|
||||
private const string SettingKey = "heartbeat.interval.seconds";
|
||||
private const int DefaultIntervalSeconds = 30;
|
||||
private const int MinimumIntervalSeconds = 5;
|
||||
private const int MaximumIntervalSeconds = 300;
|
||||
private const int SchedulerGraceSeconds = 60;
|
||||
private const int MinimumTimeoutSeconds = 90;
|
||||
|
||||
private readonly int _globalIntervalSeconds;
|
||||
private readonly IReadOnlyDictionary<Guid, int> _agentIntervals;
|
||||
|
||||
private HeartbeatTimeoutPolicy(int globalIntervalSeconds, IReadOnlyDictionary<Guid, int> agentIntervals)
|
||||
{
|
||||
_globalIntervalSeconds = globalIntervalSeconds;
|
||||
_agentIntervals = agentIntervals;
|
||||
}
|
||||
|
||||
public static async Task<HeartbeatTimeoutPolicy> LoadAsync(AppDbContext db, CancellationToken ct)
|
||||
{
|
||||
var globalValue = await db.AppSettings.AsNoTracking()
|
||||
.Where(setting => setting.Key == SettingKey)
|
||||
.Select(setting => setting.Value)
|
||||
.FirstOrDefaultAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
var agentValues = await db.AgentSettings.AsNoTracking()
|
||||
.Where(setting => setting.Key == SettingKey)
|
||||
.Select(setting => new { setting.AgentId, setting.Value })
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var globalInterval = ParseInterval(globalValue, DefaultIntervalSeconds);
|
||||
var overrides = agentValues.ToDictionary(
|
||||
setting => setting.AgentId,
|
||||
setting => ParseInterval(setting.Value, MaximumIntervalSeconds));
|
||||
return new HeartbeatTimeoutPolicy(globalInterval, overrides);
|
||||
}
|
||||
|
||||
public int GetTimeoutSeconds(Guid agentId)
|
||||
{
|
||||
var interval = _agentIntervals.GetValueOrDefault(agentId, _globalIntervalSeconds);
|
||||
return Math.Max(MinimumTimeoutSeconds, interval * 2 + SchedulerGraceSeconds);
|
||||
}
|
||||
|
||||
public static int MaximumTimeoutSeconds => MaximumIntervalSeconds * 2 + SchedulerGraceSeconds;
|
||||
|
||||
private static int ParseInterval(string? value, int fallback) =>
|
||||
int.TryParse(value, out var interval) && interval is >= MinimumIntervalSeconds and <= MaximumIntervalSeconds
|
||||
? interval
|
||||
: fallback;
|
||||
}
|
||||
@@ -45,7 +45,7 @@
|
||||
<MudItem xs="12" md="6">
|
||||
<MudNumericField T="int?" Label="Intervalle de heartbeat (secondes)" Variant="Variant.Outlined"
|
||||
Value="@(int.TryParse(GetValue("heartbeat.interval.seconds"), out var h) ? h : null)"
|
||||
ValueChanged="OnHeartbeatChanged" Min="5" Max="3600"
|
||||
ValueChanged="OnHeartbeatChanged" Min="5" Max="300"
|
||||
HelperText="Fréquence de la remontée d'état des agents vers le central." />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
@@ -255,7 +255,16 @@ public class SettingsController : ControllerBase
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
|
||||
await _broadcast.NotifyAgentSettingChanged(agentId, key, string.Empty, ct);
|
||||
var valueToApply = "";
|
||||
if (key.Equals("heartbeat.interval.seconds", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
valueToApply = "30";
|
||||
var globalSetting = await _mediator.Send(new GetSettingByKeyQuery("heartbeat.interval.seconds"), ct);
|
||||
if (globalSetting.IsSuccess && globalSetting.Data is not null)
|
||||
valueToApply = globalSetting.Data.Value;
|
||||
}
|
||||
|
||||
await _broadcast.NotifyAgentSettingChanged(agentId, key, valueToApply, ct);
|
||||
_logger.LogInformation("Removed agent override Agent={AgentId}, {Key}", agentId, key);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
@@ -296,6 +296,10 @@ public partial class Program
|
||||
|
||||
private static async Task SeedIntegrationSettingsAsync(AppDbContext groupDb, HashSet<string> existingKeys)
|
||||
{
|
||||
var heartbeatInterval = Environment.GetEnvironmentVariable("HEARTBEAT__INTERVAL_SECONDS");
|
||||
if (!int.TryParse(heartbeatInterval, out var heartbeatSeconds) || heartbeatSeconds is < 5 or > 300)
|
||||
heartbeatInterval = "30";
|
||||
|
||||
var defaults = new Dictionary<string, string?>
|
||||
{
|
||||
["ntfy.baseUrl"] = Environment.GetEnvironmentVariable("NTFY__BASE_URL") ?? "https://ntfy.sh",
|
||||
@@ -312,9 +316,17 @@ public partial class Program
|
||||
["ai.detection.enabled"] = Environment.GetEnvironmentVariable("AI__DETECTION__ENABLED") ?? "true",
|
||||
["log.level"] = Environment.GetEnvironmentVariable("LOG__LEVEL") ?? "info",
|
||||
["log.retentionDays"] = Environment.GetEnvironmentVariable("LOG__RETENTION_DAYS") ?? "7",
|
||||
["heartbeat.interval.seconds"] = Environment.GetEnvironmentVariable("HEARTBEAT__INTERVAL_SECONDS") ?? "30",
|
||||
["heartbeat.interval.seconds"] = heartbeatInterval,
|
||||
["sentry.enabled"] = "true",
|
||||
};
|
||||
|
||||
var existingHeartbeatSetting = await groupDb.AppSettings
|
||||
.FirstOrDefaultAsync(setting => setting.Key == "heartbeat.interval.seconds");
|
||||
if (existingHeartbeatSetting is not null &&
|
||||
(!int.TryParse(existingHeartbeatSetting.Value, out var storedHeartbeatSeconds) ||
|
||||
storedHeartbeatSeconds is < 5 or > 300))
|
||||
existingHeartbeatSetting.UpdateValue(heartbeatInterval);
|
||||
|
||||
foreach (var (key, value) in defaults)
|
||||
{
|
||||
if (existingKeys.Contains(key)) continue;
|
||||
|
||||
Reference in new issue
Block a user