|
| 1 | +using System.Net.NetworkInformation; |
| 2 | +using System.Net.Sockets; |
| 3 | +using System.Reflection; |
| 4 | +using LogMkCommon; |
| 5 | + |
| 6 | +namespace LogMkAgent.Services; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Periodically posts a heartbeat with runtime stats and pulls down the latest |
| 10 | +/// agent-specific config so log filtering and batching can be tuned from the |
| 11 | +/// web portal without restarting the agent. |
| 12 | +/// </summary> |
| 13 | +public class AgentRegistrationService : BackgroundService |
| 14 | +{ |
| 15 | + private readonly LogApiClient _apiClient; |
| 16 | + private readonly BatchingService _batchingService; |
| 17 | + private readonly LogWatcher _logWatcher; |
| 18 | + private readonly ILogger<AgentRegistrationService> _logger; |
| 19 | + |
| 20 | + private readonly TimeSpan _heartbeatInterval = TimeSpan.FromSeconds(30); |
| 21 | + private readonly TimeSpan _configPollInterval = TimeSpan.FromSeconds(60); |
| 22 | + |
| 23 | + private readonly DateTime _startedAt = DateTime.UtcNow; |
| 24 | + private readonly string _agentId; |
| 25 | + private readonly string _hostname; |
| 26 | + private readonly string? _version; |
| 27 | + private readonly string? _ipAddress; |
| 28 | + |
| 29 | + public AgentRegistrationService( |
| 30 | + LogApiClient apiClient, |
| 31 | + BatchingService batchingService, |
| 32 | + LogWatcher logWatcher, |
| 33 | + ILogger<AgentRegistrationService> logger) |
| 34 | + { |
| 35 | + _apiClient = apiClient; |
| 36 | + _batchingService = batchingService; |
| 37 | + _logWatcher = logWatcher; |
| 38 | + _logger = logger; |
| 39 | + |
| 40 | + _hostname = Environment.MachineName; |
| 41 | + _agentId = _hostname; // DaemonSet → one agent per node, hostname is unique |
| 42 | + _version = Assembly.GetExecutingAssembly().GetName().Version?.ToString(); |
| 43 | + _ipAddress = TryGetLocalIp(); |
| 44 | + |
| 45 | + _logger.LogInformation("AgentRegistrationService starting: AgentId={AgentId}, Hostname={Hostname}, Version={Version}", |
| 46 | + _agentId, _hostname, _version); |
| 47 | + } |
| 48 | + |
| 49 | + protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| 50 | + { |
| 51 | + // Pull config once on startup before the regular polling loop |
| 52 | + await PullConfigAsync(stoppingToken).ConfigureAwait(false); |
| 53 | + |
| 54 | + var lastConfigPull = DateTime.UtcNow; |
| 55 | + |
| 56 | + while (!stoppingToken.IsCancellationRequested) |
| 57 | + { |
| 58 | + try |
| 59 | + { |
| 60 | + await SendHeartbeatAsync(stoppingToken).ConfigureAwait(false); |
| 61 | + } |
| 62 | + catch (Exception ex) |
| 63 | + { |
| 64 | + _logger.LogWarning(ex, "Heartbeat failed"); |
| 65 | + } |
| 66 | + |
| 67 | + if (DateTime.UtcNow - lastConfigPull >= _configPollInterval) |
| 68 | + { |
| 69 | + try |
| 70 | + { |
| 71 | + await PullConfigAsync(stoppingToken).ConfigureAwait(false); |
| 72 | + lastConfigPull = DateTime.UtcNow; |
| 73 | + } |
| 74 | + catch (Exception ex) |
| 75 | + { |
| 76 | + _logger.LogWarning(ex, "Config pull failed"); |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + try |
| 81 | + { |
| 82 | + await Task.Delay(_heartbeatInterval, stoppingToken).ConfigureAwait(false); |
| 83 | + } |
| 84 | + catch (OperationCanceledException) |
| 85 | + { |
| 86 | + break; |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + private async Task SendHeartbeatAsync(CancellationToken cancellationToken) |
| 92 | + { |
| 93 | + var stats = _batchingService.GetStats(); |
| 94 | + var heartbeat = new AgentHeartbeat |
| 95 | + { |
| 96 | + AgentId = _agentId, |
| 97 | + Hostname = _hostname, |
| 98 | + Version = _version, |
| 99 | + IpAddress = _ipAddress, |
| 100 | + StartedAt = _startedAt, |
| 101 | + LastBatchSentAt = stats.LastSuccessfulSend, |
| 102 | + QueuedItems = stats.QueuedItems, |
| 103 | + TotalItemsProcessed = stats.TotalItemsProcessed, |
| 104 | + TotalBatchesSent = stats.TotalBatchesSent, |
| 105 | + TotalFailures = stats.TotalFailures, |
| 106 | + TotalDropped = stats.TotalDropped, |
| 107 | + CircuitBreakerState = stats.CircuitBreakerState |
| 108 | + }; |
| 109 | + |
| 110 | + var response = await _apiClient.PostJsonAsync("api/agents/heartbeat", heartbeat, cancellationToken) |
| 111 | + .ConfigureAwait(false); |
| 112 | + |
| 113 | + if (!response.IsSuccessStatusCode) |
| 114 | + { |
| 115 | + _logger.LogDebug("Heartbeat returned non-success status {StatusCode}", response.StatusCode); |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + private async Task PullConfigAsync(CancellationToken cancellationToken) |
| 120 | + { |
| 121 | + try |
| 122 | + { |
| 123 | + var config = await _apiClient.GetDataAsync<AgentConfig>($"api/agents/{Uri.EscapeDataString(_agentId)}/config") |
| 124 | + .ConfigureAwait(false); |
| 125 | + |
| 126 | + if (config == null) |
| 127 | + { |
| 128 | + _logger.LogDebug("No agent config returned for {AgentId}", _agentId); |
| 129 | + return; |
| 130 | + } |
| 131 | + |
| 132 | + _logWatcher.ApplyConfig(config); |
| 133 | + _batchingService.ApplyConfig(config); |
| 134 | + } |
| 135 | + catch (HttpRequestException ex) |
| 136 | + { |
| 137 | + _logger.LogDebug(ex, "Could not reach API to pull config"); |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + private static string? TryGetLocalIp() |
| 142 | + { |
| 143 | + try |
| 144 | + { |
| 145 | + foreach (var ni in NetworkInterface.GetAllNetworkInterfaces()) |
| 146 | + { |
| 147 | + if (ni.OperationalStatus != OperationalStatus.Up) continue; |
| 148 | + if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue; |
| 149 | + |
| 150 | + foreach (var ip in ni.GetIPProperties().UnicastAddresses) |
| 151 | + { |
| 152 | + if (ip.Address.AddressFamily == AddressFamily.InterNetwork) |
| 153 | + { |
| 154 | + return ip.Address.ToString(); |
| 155 | + } |
| 156 | + } |
| 157 | + } |
| 158 | + } |
| 159 | + catch |
| 160 | + { |
| 161 | + // best-effort |
| 162 | + } |
| 163 | + return null; |
| 164 | + } |
| 165 | +} |
0 commit comments