121 lines
4.4 KiB
C#
121 lines
4.4 KiB
C#
using System.Security.Cryptography;
|
|||
|
|
using System.Text;
|
||
|
|
using Heimdall.Application.Common;
|
||
|
|
using Heimdall.Application.DTOs;
|
||
|
|
using Heimdall.Application.Services;
|
||
|
|
using Heimdall.Domain.Entities;
|
||
|
|
using Heimdall.Domain.Enums;
|
||
|
|
using Heimdall.Infrastructure.Data;
|
||
|
|
using Heimdall.Infrastructure.Security;
|
||
|
|
using Microsoft.EntityFrameworkCore;
|
||
|
|
|
||
|
|
namespace Heimdall.Infrastructure.Services;
|
||
|
|
|
||
|
|
public class AgentService : IAgentService
|
||
|
|
{
|
||
|
|
private readonly AppDbContext _db;
|
||
|
|
|
||
|
|
public AgentService(AppDbContext db) => _db = db;
|
||
|
|
|
||
|
|
public async Task<ServiceResult<RegisterAgentResponse>> RegisterAsync(
|
||
|
|
RegisterAgentRequest request, string? apiKey, CancellationToken ct)
|
||
|
|
{
|
||
|
|
// Find site by registration token hash
|
||
|
|
var tokenHash = Convert.ToHexString(
|
||
|
|
SHA256.HashData(Encoding.UTF8.GetBytes(request.Token))).ToLowerInvariant();
|
||
|
|
|
||
|
|
var site = await _db.Sites
|
||
|
|
.FirstOrDefaultAsync(s => s.RegistrationTokenHash == tokenHash
|
||
|
|
&& s.TokenExpiresAt > DateTime.UtcNow, ct);
|
||
|
|
|
||
|
|
if (site is null)
|
||
|
|
return ServiceResult<RegisterAgentResponse>.Unauthorized("Invalid or expired registration token");
|
||
|
|
|
||
|
|
// Check for duplicate registration
|
||
|
|
var existing = await _db.Agents
|
||
|
|
.AnyAsync(a => a.SiteId == site.Id && a.Hostname == request.Hostname, ct);
|
||
|
|
|
||
|
|
if (existing)
|
||
|
|
return ServiceResult<RegisterAgentResponse>.Conflict(
|
||
|
|
"An agent with this hostname is already registered for this site");
|
||
|
|
|
||
|
|
// Generate API key for the agent
|
||
|
|
var (plainKey, prefix, hash) = ApiKeyAuthenticationHandler.GenerateApiKey();
|
||
|
|
|
||
|
|
var agent = new Agent(site.Id, request.Hostname, request.Hostname, request.Version);
|
||
|
|
agent.Register(hash, prefix);
|
||
|
|
agent.UpdateHeartbeat(request.PublicIp);
|
||
|
|
_db.Agents.Add(agent);
|
||
|
|
|
||
|
|
// Store API key
|
||
|
|
var apiKeyEntity = new ApiKey(hash, prefix, site.Id);
|
||
|
|
_db.ApiKeys.Add(apiKeyEntity);
|
||
|
|
|
||
|
|
// Clear the registration token (single use)
|
||
|
|
site.ClearRegistrationToken();
|
||
|
|
|
||
|
|
await _db.SaveChangesAsync(ct);
|
||
|
|
|
||
|
|
// Audit log
|
||
|
|
_db.AuditLogs.Add(new AuditLog(null, "Agent.Registered", "Agent",
|
||
|
|
agent.Id.ToString(), ipAddress: request.PublicIp));
|
||
|
|
await _db.SaveChangesAsync(ct);
|
||
|
|
|
||
|
|
return ServiceResult<RegisterAgentResponse>.Success(
|
||
|
|
new RegisterAgentResponse(agent.Id, plainKey, prefix));
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<ServiceResult> HeartbeatAsync(Guid agentId, AgentHeartbeatRequest request, CancellationToken ct)
|
||
|
|
{
|
||
|
|
var agent = await _db.Agents.FindAsync([agentId], ct);
|
||
|
|
if (agent is null)
|
||
|
|
return ServiceResult.NotFound("Agent not found");
|
||
|
|
|
||
|
|
agent.UpdateHeartbeat(request.PublicIp);
|
||
|
|
|
||
|
|
if (request.HasGpu.HasValue || request.CpuCores.HasValue)
|
||
|
|
{
|
||
|
|
var gpuType = Enum.TryParse<GpuAcceleration>(request.GpuType, true, out var gpu)
|
||
|
|
? gpu : GpuAcceleration.None;
|
||
|
|
|
||
|
|
agent.UpdateCapabilities(
|
||
|
|
request.HasGpu ?? false,
|
||
|
|
request.CpuCores ?? 0,
|
||
|
|
request.MemoryMb ?? 0,
|
||
|
|
gpuType);
|
||
|
|
}
|
||
|
|
|
||
|
|
await _db.SaveChangesAsync(ct);
|
||
|
|
return ServiceResult.Success();
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<ServiceResult<AgentResponse>> GetByIdAsync(Guid id, CancellationToken ct)
|
||
|
|
{
|
||
|
|
var agent = await _db.Agents.FindAsync([id], ct);
|
||
|
|
if (agent is null)
|
||
|
|
return ServiceResult<AgentResponse>.NotFound("Agent not found");
|
||
|
|
|
||
|
|
return ServiceResult<AgentResponse>.Success(MapResponse(agent));
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<ServiceResult<PagedResult<AgentResponse>>> ListBySiteAsync(
|
||
|
|
Guid siteId, int page, int pageSize, CancellationToken ct)
|
||
|
|
{
|
||
|
|
var query = _db.Agents.Where(a => a.SiteId == siteId).OrderBy(a => a.Name);
|
||
|
|
|
||
|
|
var total = await query.CountAsync(ct);
|
||
|
|
var items = await query
|
||
|
|
.Skip((page - 1) * pageSize)
|
||
|
|
.Take(pageSize)
|
||
|
|
.Select(a => MapResponse(a))
|
||
|
|
.ToListAsync(ct);
|
||
|
|
|
||
|
|
return ServiceResult<PagedResult<AgentResponse>>.Success(
|
||
|
|
new PagedResult<AgentResponse>(items, total, page, pageSize));
|
||
|
|
}
|
||
|
|
|
||
|
|
private static AgentResponse MapResponse(Agent a) => new(
|
||
|
|
a.Id, a.SiteId, a.Name, a.Hostname, a.Version, a.Status,
|
||
|
|
a.LastHeartbeat, a.PublicIp, a.HasGpu, a.CpuCores, a.MemoryMb,
|
||
|
|
a.GpuType.ToString(), a.CreatedAt);
|
||
|
|
}
|