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
269 lines
12 KiB
C#
269 lines
12 KiB
C#
using Heimdall.Application.Agents.Commands.RegisterAgent;
|
|
using Heimdall.Application.Agents.Commands.Heartbeat;
|
|
using Heimdall.Application.Agents.Commands.DeleteAgent;
|
|
using Heimdall.Application.AgentDiscovery.Commands.SubmitAgentDiscovery;
|
|
using Heimdall.Application.Agents.Queries.GetAgent;
|
|
using Heimdall.Application.Agents.Queries.GetAgentsBySite;
|
|
using Heimdall.Application.Agents.Queries.GetAllAgents;
|
|
using Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs;
|
|
using Heimdall.Application.AgentLogs.Queries.GetAgentLogs;
|
|
using Heimdall.Application.Inventory.Queries.GetAgentMetricHistory;
|
|
using Heimdall.Application.Cameras.Commands.ReportCameraStatus;
|
|
using Heimdall.Application.DTOs;
|
|
using Heimdall.Domain.Enums;
|
|
using Heimdall.Infrastructure.Security;
|
|
using MediatR;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.RateLimiting;
|
|
|
|
namespace Heimdall.Api.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/agents")]
|
|
[EnableRateLimiting("Api")]
|
|
public class AgentsController : ControllerBase
|
|
{
|
|
/// <summary>Query parameters for agent log retrieval.</summary>
|
|
public record AgentLogsQuery(
|
|
[FromQuery] int Page = 1,
|
|
[FromQuery] int PageSize = 50,
|
|
[FromQuery] string? Level = null,
|
|
[FromQuery] DateTime? From = null,
|
|
[FromQuery] DateTime? To = null,
|
|
[FromQuery] string? Search = null);
|
|
|
|
private readonly IMediator _mediator;
|
|
|
|
public AgentsController(IMediator mediator) => _mediator = mediator;
|
|
|
|
/// <summary>Register an agent using a site registration token.</summary>
|
|
[AllowAnonymous]
|
|
[HttpPost("register")]
|
|
[ProducesResponseType(typeof(RegisterAgentResponse), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
|
public async Task<IActionResult> Register(
|
|
[FromBody] RegisterAgentRequest request, CancellationToken ct)
|
|
{
|
|
var command = new RegisterAgentCommand(request.Token, request.Hostname, request.Version, request.PublicIp);
|
|
var result = await _mediator.Send(command, ct);
|
|
return result.IsSuccess
|
|
? Ok(result.Data)
|
|
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
|
|
}
|
|
|
|
/// <summary>Send heartbeat from agent (API Key auth).</summary>
|
|
[Authorize(AuthenticationSchemes = "ApiKey")]
|
|
[HttpPost("{id:guid}/heartbeat")]
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
public async Task<IActionResult> Heartbeat(
|
|
Guid id, [FromBody] AgentHeartbeatRequest request, CancellationToken ct)
|
|
{
|
|
GpuAcceleration? gpuType = request.GpuType is not null && Enum.TryParse<GpuAcceleration>(request.GpuType, true, out var parsed) ? parsed : null;
|
|
var command = new HeartbeatCommand(
|
|
id,
|
|
request.PublicIp,
|
|
request.HasGpu,
|
|
request.CpuCores,
|
|
(int?)request.MemoryMb,
|
|
gpuType,
|
|
request.GpuName,
|
|
request.VramMb,
|
|
request.GpuLoadPercent,
|
|
request.VramUsageBytes,
|
|
request.IsOffline,
|
|
request.CpuUsagePercent,
|
|
request.MemoryUsageBytes,
|
|
request.DiskUsagePercent,
|
|
request.UptimeSeconds,
|
|
// CPU inventory
|
|
request.CpuVendor,
|
|
request.CpuModel,
|
|
request.CpuArchitecture,
|
|
request.PhysicalCores,
|
|
request.LogicalCores,
|
|
request.ThreadsPerCore,
|
|
request.CpuFrequencyMhz,
|
|
request.CpuFlags,
|
|
request.CpuCacheBytes,
|
|
request.ContainerCpuLimit,
|
|
// Memory inventory
|
|
request.MemTotalBytes,
|
|
request.MemAvailableBytes,
|
|
request.SwapTotalBytes,
|
|
request.SwapFreeBytes,
|
|
request.ContainerMemoryLimitBytes,
|
|
// Disk inventory
|
|
request.DiskInventoryJson,
|
|
// GPU inventory
|
|
request.GpuInventoryJson,
|
|
// Host info
|
|
request.OsName,
|
|
request.KernelVersion,
|
|
request.Arch,
|
|
request.UptimeMachineSeconds,
|
|
// Container info
|
|
request.ContainerId,
|
|
request.ContainerImage,
|
|
// Network & Temperature
|
|
request.NetworkInterfacesJson,
|
|
request.TemperatureJson);
|
|
var result = await _mediator.Send(command, ct);
|
|
return result.IsSuccess
|
|
? Ok()
|
|
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
}
|
|
|
|
/// <summary>Submit network scan results from agent (API Key auth).</summary>
|
|
/// <remarks>
|
|
/// The agent probes its local subnet (ports, HTTP, ONVIF WS-Discovery, ARP)
|
|
/// and posts the raw devices here; the Central enriches each candidate with
|
|
/// the site's credential pool (authenticated ONVIF) and builds stream URLs.
|
|
/// </remarks>
|
|
[Authorize(AuthenticationSchemes = "ApiKey")]
|
|
[HttpPost("{id:guid}/discovery")]
|
|
[ProducesResponseType(typeof(AgentDiscoverySubmitResponse), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> SubmitDiscovery(
|
|
Guid id, [FromBody] IReadOnlyList<AgentDiscoveredDevice> devices, CancellationToken ct)
|
|
{
|
|
var command = new SubmitAgentDiscoveryCommand(id, devices);
|
|
var result = await _mediator.Send(command, ct);
|
|
return result.IsSuccess
|
|
? Ok(result.Data)
|
|
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
|
}
|
|
|
|
/// <summary>Report a camera's live status from an agent (API Key auth).</summary>
|
|
/// <remarks>
|
|
/// Called by the agent when a capture starts, ffmpeg fails, or a camera is
|
|
/// removed — keeps Camera.Status in sync with reality (Online/Error/…).
|
|
/// </remarks>
|
|
[Authorize(AuthenticationSchemes = "ApiKey")]
|
|
[HttpPut("{id:guid}/cameras/{cameraId:guid}/status")]
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> ReportCameraStatus(
|
|
Guid id, Guid cameraId, [FromBody] ReportCameraStatusRequest request, CancellationToken ct)
|
|
{
|
|
if (!Enum.TryParse<CameraStatus>(request.Status, true, out var status))
|
|
return BadRequest(new { error = $"Invalid status: {request.Status}" });
|
|
|
|
var command = new ReportCameraStatusCommand(id, cameraId, status);
|
|
var result = await _mediator.Send(command, ct);
|
|
return result.IsSuccess
|
|
? Ok()
|
|
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
}
|
|
|
|
/// <summary>Get agent details (JWT auth).</summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
|
[HttpGet("{id:guid}")]
|
|
[ProducesResponseType(typeof(AgentResponse), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
|
{
|
|
var result = await _mediator.Send(new GetAgentQuery(id), ct);
|
|
return result.IsSuccess
|
|
? Ok(result.Data)
|
|
: NotFound(new { error = result.Error });
|
|
}
|
|
|
|
/// <summary>List agents for a site.</summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
|
[HttpGet("by-site/{siteId:guid}")]
|
|
[ProducesResponseType(typeof(PagedResult<AgentResponse>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
public async Task<IActionResult> ListBySite(
|
|
Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
|
|
{
|
|
var result = await _mediator.Send(new GetAgentsBySiteQuery(siteId, page, pageSize), ct);
|
|
if (!result.IsSuccess)
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
return Ok(result.Data);
|
|
}
|
|
|
|
/// <summary>Submit a batch of log entries from an agent (API Key auth).</summary>
|
|
[Authorize(AuthenticationSchemes = "ApiKey")]
|
|
[HttpPost("{id:guid}/logs")]
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> SubmitLogs(
|
|
Guid id, [FromBody] SubmitAgentLogsRequest request, CancellationToken ct)
|
|
{
|
|
var command = new SubmitAgentLogsCommand(id, request.Entries);
|
|
var result = await _mediator.Send(command, ct);
|
|
return result.IsSuccess
|
|
? Ok()
|
|
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
}
|
|
|
|
/// <summary>Get agent log entries (JWT auth).</summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
|
[HttpGet("{id:guid}/logs")]
|
|
[ProducesResponseType(typeof(PagedResult<AgentLogEntryDto>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
public async Task<IActionResult> GetLogs(
|
|
Guid id,
|
|
AgentLogsQuery query,
|
|
CancellationToken ct)
|
|
{
|
|
var result = await _mediator.Send(
|
|
new GetAgentLogsQuery(id, query.Page, query.PageSize, query.Level, query.From, query.To, query.Search), ct);
|
|
if (!result.IsSuccess)
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
return Ok(result.Data);
|
|
}
|
|
|
|
/// <summary>Get bounded historical metrics for an Agent.</summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
|
[HttpGet("{id:guid}/metrics/history")]
|
|
[ProducesResponseType(typeof(IReadOnlyList<AgentMetricHistoryPoint>), StatusCodes.Status200OK)]
|
|
public async Task<IActionResult> GetMetricHistory(Guid id, [FromQuery] string range = "24h", CancellationToken ct = default)
|
|
{
|
|
var result = await _mediator.Send(new GetAgentMetricHistoryQuery(id, range), ct);
|
|
if (!result.IsSuccess)
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
return Ok(result.Data);
|
|
}
|
|
|
|
/// <summary>List all agents across all sites.</summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
|
[HttpGet]
|
|
[ProducesResponseType(typeof(PagedResult<AgentResponse>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
public async Task<IActionResult> ListAll(
|
|
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
|
|
{
|
|
var result = await _mediator.Send(new GetAllAgentsQuery(page, pageSize, await GetAllowedSites(ct)), ct);
|
|
if (!result.IsSuccess)
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
return Ok(result.Data);
|
|
}
|
|
|
|
/// <summary>Soft-delete an agent (spec Phase 10) and unassign its cameras.</summary>
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)]
|
|
[HttpDelete("{id:guid}")]
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
|
{
|
|
var command = new DeleteAgentCommand(id);
|
|
var result = await _mediator.Send(command, ct);
|
|
return result.IsSuccess
|
|
? Ok()
|
|
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
|
}
|
|
private async Task<List<Guid>> GetAllowedSites(CancellationToken ct)
|
|
{
|
|
var access = HttpContext.RequestServices.GetRequiredService<Heimdall.Api.Security.ResourceAccess>();
|
|
var requester = await access.ResolveAsync(User, ct);
|
|
return requester is null ? [] : await access.FullSiteIdsAsync(requester, ct);
|
|
}
|
|
|
|
}
|