forked from CMS-Enterprise/SONAR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
543 lines (484 loc) · 20.4 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Cms.BatCave.Sonar.Agent.Configuration;
using Cms.BatCave.Sonar.Agent.HealthChecks;
using Cms.BatCave.Sonar.Agent.HealthChecks.Metrics;
using Cms.BatCave.Sonar.Agent.Options;
using Cms.BatCave.Sonar.Agent.ServiceConfig;
using Cms.BatCave.Sonar.Agent.Telemetry;
using Cms.BatCave.Sonar.Agent.VersionChecks;
using Cms.BatCave.Sonar.Configuration;
using Cms.BatCave.Sonar.Enumeration;
using Cms.BatCave.Sonar.Exceptions;
using Cms.BatCave.Sonar.Factories;
using Cms.BatCave.Sonar.Logger;
using Cms.BatCave.Sonar.Loki;
using Cms.BatCave.Sonar.Models;
using CommandLine;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using PrometheusQuerySdk;
namespace Cms.BatCave.Sonar.Agent;
internal class Program {
private static Task<Int32> Main(String[] args) {
// Command Line Parsing
var parser = new Parser(settings => {
// Assume that unknown arguments will be handled by the dotnet Command-line configuration
// provider
settings.IgnoreUnknownArguments = true;
settings.HelpWriter = Console.Error;
});
var parserResult = parser.ParseArguments<SonarAgentOptions>(args);
return parserResult
.MapResult(
RunAgent,
notParsedFunc: _ => Task.FromResult(1)
);
}
private static async Task<Int32> RunAgent(SonarAgentOptions opts) {
// API Configuration
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile(
Path.Combine(opts.AppSettingsLocation, "appsettings.json"),
optional: true,
reloadOnChange: true)
.AddJsonFile(
Path.Combine(opts.AppSettingsLocation,
$"appsettings.{Environment.GetEnvironmentVariable("ENVIRONMENT") ?? "Development"}.json"),
optional: true,
reloadOnChange: true)
.AddEnvironmentVariables();
IConfigurationRoot configuration = builder.Build();
// Configure logging
using var loggerFactory = LoggerFactory.Create(loggingBuilder => {
loggingBuilder
.AddConfiguration(configuration.GetSection("Logging"))
.AddConsole(options => options.FormatterName = nameof(CustomFormatter))
.AddConsoleFormatter<CustomFormatter, LoggingCustomOptions>();
});
var logger = loggerFactory.CreateLogger<Program>();
// Create watcher for each configuration file
var relativePathRegex = new Regex(@"^\./");
var disposables = new List<IDisposable>();
foreach (var provider in configuration.Providers) {
if (provider is FileConfigurationProvider fileProvider &&
fileProvider.Source.FileProvider != null &&
fileProvider.Source.Path != null) {
logger.LogInformation("WATCHING {ConfigFileName}",
fileProvider.Source.FileProvider.GetFileInfo(fileProvider.Source.Path).PhysicalPath);
var configFileName = relativePathRegex.Replace(fileProvider.Source.Path, replacement: "");
disposables.Add(
new ConfigurationWatcher(provider).CreateConfigWatcher(Directory.GetCurrentDirectory(), configFileName));
}
}
RecordOptionsManager<ApiConfiguration> apiConfig;
RecordOptionsManager<PrometheusConfiguration> promConfig;
RecordOptionsManager<LokiConfiguration> lokiConfig;
RecordOptionsManager<AgentConfiguration> agentConfig;
RecordOptionsManager<HealthCheckQueueProcessorConfiguration> httpHealthCheckConfiguration;
RecordOptionsManager<MetricServerConfiguration> metricsConfig;
try {
apiConfig = Dependencies.CreateRecordOptions<ApiConfiguration>(
configuration, "ApiConfig", loggerFactory);
promConfig = Dependencies.CreateRecordOptions<PrometheusConfiguration>(
configuration, "Prometheus", loggerFactory);
lokiConfig = Dependencies.CreateRecordOptions<LokiConfiguration>(
configuration, "Loki", loggerFactory);
agentConfig = Dependencies.CreateRecordOptions<AgentConfiguration>(
configuration, "AgentConfig", loggerFactory);
httpHealthCheckConfiguration = Dependencies.CreateRecordOptions<HealthCheckQueueProcessorConfiguration>(
configuration, "HttpHealthChecks", loggerFactory);
metricsConfig = Dependencies.CreateRecordOptions<MetricServerConfiguration>(
configuration, "MetricServer", loggerFactory);
} catch (RecordBindingException ex) {
logger.LogError(ex, "Invalid sonar-agent configuration. {_Message}", ex.Message);
return 1;
}
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("Sonar.HealthStatus")
.AddMeter("System.Runtime")
.AddRuntimeInstrumentation()
.AddPrometheusHttpListener(options => {
options.UriPrefixes = new[] {
$"http://*:{metricsConfig.Value.Port}/"
};
})
.Build();
using var listener = new RuntimeCounterEventListener();
// Create cancellation source, token, new task
using var source = new CancellationTokenSource();
var token = source.Token;
// Event handler for SIGINT
// Traps SIGINT to perform necessary cleanup
Console.CancelKeyPress += delegate {
logger.Log(LogLevel.Information, "\nSIGINT received, begin cleanup...");
// ReSharper disable once AccessToDisposedClosure
// (this is fine, once Program exits this isn't going to get triggered).
source?.Cancel();
};
var configFiles = opts.ServiceConfigFiles.ToArray();
var configSources = configFiles.Length > 0 ?
new[] {
new LocalFileServiceConfigSource(agentConfig.Value.DefaultTenant, configFiles)
} :
Enumerable.Empty<IServiceConfigSource>();
var kubeClientFactory = new KubeClientFactory(loggerFactory.CreateLogger<KubeClientFactory>());
if (opts.KubernetesConfigurationOption) {
var kubeClient = kubeClientFactory.CreateKubeClient(agentConfig.Value.InClusterConfig);
disposables.Add(kubeClient);
configSources =
configSources.Append(
new KubernetesConfigSource(kubeClient, loggerFactory.CreateLogger<KubernetesConfigSource>())
);
}
(IDisposable, ISonarClient) SonarClientFactory() {
var http = new HttpClient();
return (http, new SonarClient(apiConfig, http));
}
var errorReportsHelper = new ErrorReportsHelper(
SonarClientFactory,
loggerFactory.CreateLogger<ErrorReportsHelper>());
var configurationHelper = new ConfigurationHelper(
new AggregateServiceConfigSource(configSources),
SonarClientFactory,
loggerFactory.CreateLogger<ConfigurationHelper>(),
errorReportsHelper
);
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
UnhandledExceptionErrorReportHandler(e.ExceptionObject, logger, errorReportsHelper,
apiConfig.Value.Environment,
token).Wait();
IDictionary<String, ServiceHierarchyConfiguration> servicesHierarchy;
try {
// Load and merge configs
servicesHierarchy = await configurationHelper.LoadAndValidateJsonServiceConfigAsync(
apiConfig.Value.Environment,
token);
} catch (Exception ex) when (ex is InvalidConfigurationException or ArgumentException) {
logger.LogError(ex, "Invalid Service Configuration: {_Message}", ex.Message);
return 1;
}
// Configure service hierarchy
logger.LogInformation("Configuring services....");
const Int32 threshold = 10;
var isSuccess = false;
var retryDelay = TimeSpan.FromSeconds(30);
for (var attempts = 0; attempts <= threshold; attempts++) {
logger.LogInformation("Saving configuration, attempt {Attempts}", attempts);
try {
await CreateOrUpdateEnvironment(apiConfig, agentConfig, logger, token);
await configurationHelper.ConfigureServicesAsync(apiConfig.Value.Environment, servicesHierarchy, token);
isSuccess = true;
break;
} catch (HttpRequestException ex) {
logger.LogError(ex,
"HTTP Request Exception Code {StatusCode}: {_Message}",
ex.StatusCode,
ex.Message);
// create error report
await errorReportsHelper.CreateErrorReport(
apiConfig.Value.Environment,
new ErrorReportDetails(
DateTime.UtcNow,
null,
null,
null,
AgentErrorLevel.Error,
AgentErrorType.SaveConfiguration,
ex.Message,
null,
null),
token);
} catch (ApiException ex) {
logger.LogError(ex,
"SONAR API Returned an Error {StatusCode}: {_Message}",
ex.StatusCode,
ex.Message);
// create error report
await errorReportsHelper.CreateErrorReport(
apiConfig.Value.Environment,
new ErrorReportDetails(
DateTime.UtcNow,
null,
null,
null,
AgentErrorLevel.Error,
AgentErrorType.SaveConfiguration,
ex.Message,
null,
null),
token);
}
await Task.Delay(retryDelay, token);
}
if (!isSuccess) {
var maxConfigSavingErrMessage = "Maximum number of attempts reached for configuration saving";
logger.LogError(maxConfigSavingErrMessage);
await errorReportsHelper.CreateErrorReport(apiConfig.Value.Environment,
new ErrorReportDetails(
DateTime.UtcNow,
null,
null,
null,
AgentErrorLevel.Fatal,
AgentErrorType.SaveConfiguration,
maxConfigSavingErrMessage,
null,
null),
token);
return 1;
}
logger.LogInformation("Initializing SONAR Agent...");
// Create HealthCheck Queue Processors
// Prometheus client
HttpClient CreatePrometheusHttpClient() {
var promHttpClient = new HttpClient();
promHttpClient.Timeout = TimeSpan.FromSeconds(agentConfig.Value.AgentInterval);
promHttpClient.BaseAddress = new Uri(
$"{promConfig.Value.Protocol}://{promConfig.Value.Host}:{promConfig.Value.Port}/");
return promHttpClient;
}
var promClient = new PrometheusClient(CreatePrometheusHttpClient);
// Loki Client
HttpClient CreateLokiHttpClient() {
var lokiHttpClient = new HttpClient();
lokiHttpClient.Timeout = TimeSpan.FromSeconds(agentConfig.Value.AgentInterval);
lokiHttpClient.BaseAddress = new Uri(
$"{lokiConfig.Value.Protocol}://{lokiConfig.Value.Host}:{lokiConfig.Value.Port}/");
return lokiHttpClient;
}
var lokiClient = new LokiClient(CreateLokiHttpClient);
using var httpHealthCheckQueue = new HealthCheckQueueProcessor<HttpHealthCheckDefinition>(
new HttpHealthCheckEvaluator(
agentConfig,
loggerFactory.CreateLogger<HttpHealthCheckEvaluator>(),
SonarClientFactory),
httpHealthCheckConfiguration,
loggerFactory.CreateLogger<HealthCheckQueueProcessor<HttpHealthCheckDefinition>>()
);
using var prometheusHealthCheckQueue = new HealthCheckQueueProcessor<MetricHealthCheckDefinition>(
new MetricHealthCheckEvaluator(
new CachingMetricQueryRunner(
new ReportingMetricQueryRunner(
new PrometheusMetricQueryRunner(
promClient,
loggerFactory.CreateLogger<PrometheusMetricQueryRunner>()),
() => {
var httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromSeconds(agentConfig.Value.AgentInterval);
try {
return (httpClient, new SonarClient(apiConfig, httpClient));
} catch {
httpClient.Dispose();
throw;
}
},
loggerFactory.CreateLogger<ReportingMetricQueryRunner>())),
loggerFactory.CreateLogger<MetricHealthCheckEvaluator>()
),
agentConfig,
loggerFactory.CreateLogger<HealthCheckQueueProcessor<MetricHealthCheckDefinition>>()
);
using var lokiHealthCheckQueue = new HealthCheckQueueProcessor<MetricHealthCheckDefinition>(
new MetricHealthCheckEvaluator(
new CachingMetricQueryRunner(
new ReportingMetricQueryRunner(
new LokiMetricQueryRunner(
lokiClient,
loggerFactory.CreateLogger<LokiMetricQueryRunner>()),
() => {
var httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromSeconds(agentConfig.Value.AgentInterval);
try {
return (httpClient, new SonarClient(apiConfig, httpClient));
} catch {
httpClient.Dispose();
throw;
}
},
loggerFactory.CreateLogger<ReportingMetricQueryRunner>())),
loggerFactory.CreateLogger<MetricHealthCheckEvaluator>()
),
agentConfig,
loggerFactory.CreateLogger<HealthCheckQueueProcessor<MetricHealthCheckDefinition>>()
);
var healthCheckHelper = new HealthCheckHelper(
loggerFactory,
apiConfig,
agentConfig,
httpHealthCheckQueue,
prometheusHealthCheckQueue,
lokiHealthCheckQueue,
errorReportsHelper);
var tasks = new List<(Task Task, String Description, String? Tenant)>(new (Task, String, String?)[] {
(httpHealthCheckQueue.Run(token), "Http Health Check Queue Processor", null),
(prometheusHealthCheckQueue.Run(token), "Prometheus Health Check Queue Processor", null),
(lokiHealthCheckQueue.Run(token), "Loki Health Check Queue Processor", null),
});
// Create Version Check Queue Processors
using var versionCheckQueueProcessor = new VersionCheckQueueProcessor(agentConfig);
// Always start the HTTP Version Check processing task.
using var versionRequesterHttpClient = new HttpClient();
versionRequesterHttpClient.Timeout = TimeSpan.FromSeconds(agentConfig.Value.AgentInterval);
var httpVersionRequester = new HttpResponseBodyVersionRequester(versionRequesterHttpClient);
tasks.Add((versionCheckQueueProcessor.StartAsync(httpVersionRequester, token), "Http Version Check Processor", null));
using var sonarHttpClient = new HttpClient();
sonarHttpClient.Timeout = TimeSpan.FromSeconds(agentConfig.Value.AgentInterval);
var versionCheckHelper = new VersionCheckHelper(
loggerFactory.CreateLogger<VersionCheckHelper>(),
agentConfig,
apiConfig,
versionCheckQueueProcessor,
new SonarClient(apiConfig, sonarHttpClient));
// Run task that calls Health Check and Version Check function for every tenant
if (opts.KubernetesConfigurationOption) {
var kubeClient = kubeClientFactory.CreateKubeClient(agentConfig.Value.InClusterConfig);
var k8sWatcher = new KubernetesConfigurationMonitor(
apiConfig.Value.Environment,
configurationHelper,
kubeClient,
loggerFactory.CreateLogger<KubernetesConfigurationMonitor>(),
errorReportsHelper);
// Start the Kustomization Version Check processing task
var kustomizationVersionRequester = new FluxKustomizationVersionRequester(kubeClient);
tasks.Add((
versionCheckQueueProcessor.StartAsync(kustomizationVersionRequester, token),
"FluxKustomization Version Check Processor",
null
));
// Start the HelmRelease Version Check processing task
var helmReleaseVersionRequester = new FluxHelmReleaseVersionRequester(
kubeClient,
loggerFactory.CreateLogger<FluxHelmReleaseVersionRequester>());
tasks.Add((
versionCheckQueueProcessor.StartAsync(helmReleaseVersionRequester, token),
"FluxHelmRelease Version Check Processor",
null
));
//Start the Kubernetes resource version check processing task
var kubernetesVersionRequester = new KubernetesImageVersionRequester(kubeClient);
tasks.Add((
versionCheckQueueProcessor.StartAsync(kubernetesVersionRequester, token),
"Kubernetes resource version check processor",
null
));
disposables.Add(k8sWatcher);
disposables.Add(kubeClient);
k8sWatcher.TenantCreated += (sender, args) => {
tasks.Add((
healthCheckHelper.RunScheduledHealthCheck(args.Tenant, source, token),
"Health Check Executor",
args.Tenant
));
tasks.Add((
versionCheckHelper.RunScheduledVersionChecks(args.Tenant, source, token),
"Version Check Executor",
args.Tenant
));
};
}
// The namespace watcher will automatically start threads for existing tenants configured via
// Kubernetes, but we have to manually start the default tenant if it exists.
if (servicesHierarchy.TryGetValue(agentConfig.Value.DefaultTenant, out var services)) {
// We don't monitor local files for changes, so if there aren't any services configured,
// there is no need to start a thread.
if (services.Services.Count > 0) {
tasks.Add((
healthCheckHelper.RunScheduledHealthCheck(agentConfig.Value.DefaultTenant, source, token),
"Health Check Executor",
agentConfig.Value.DefaultTenant
));
tasks.Add((
versionCheckHelper.RunScheduledVersionChecks(agentConfig.Value.DefaultTenant, source, token),
"Version Check Executor",
agentConfig.Value.DefaultTenant
));
}
}
// Wait until user, or one of the processor threads requests cancellation
try {
await Task.Delay(Timeout.Infinite, token);
} catch (OperationCanceledException) {
// User request cancellation
}
logger.LogDebug("SONAR Agent process cancelled");
var error = false;
// This should wait for completion and raise exceptions that occurred on worker threads
foreach (var (task, desc, tenant) in tasks) {
try {
if (tenant != null) {
logger.LogDebug("Awaiting Task: {_Description} (Tenant: {Tenant}, Status: {Status})", desc, tenant, task.Status);
} else {
logger.LogDebug("Awaiting Task: {_Description} (Status: {Status})", desc, task.Status);
}
await task;
} catch (OperationCanceledException) {
// Ignore user requested cancellation errors
} catch (Exception ex) {
if (tenant != null) {
logger.LogError(ex, "Task '{_Description}' raised an unhandled exception (Tenant: {Tenant})", desc, tenant);
} else {
logger.LogError(ex, "Task '{_Description}' raised an unhandled exception", desc);
}
error = true;
}
}
foreach (var watcher in disposables) {
watcher.Dispose();
}
return error ? 1 : 0;
}
static async Task UnhandledExceptionErrorReportHandler(
Object exceptionObj,
ILogger<Program> logger,
ErrorReportsHelper errorReportsHelper,
String env,
CancellationToken token) {
var e = (Exception)exceptionObj;
// create error report
await errorReportsHelper.CreateErrorReport(env,
new ErrorReportDetails(
DateTime.UtcNow,
null,
null,
null,
AgentErrorLevel.Fatal,
AgentErrorType.Unknown,
$"Unhandled exception occured with following message: {e.Message}",
null,
null),
token);
logger.LogError(e, "Unhandled exception occured with following message: {_Message}", e.Message);
}
private static async Task CreateOrUpdateEnvironment(
IOptions<ApiConfiguration> apiConfig,
IOptions<AgentConfiguration> agentConfig,
ILogger logger,
CancellationToken cancellationToken) {
var environment = new EnvironmentModel(
name: apiConfig.Value.Environment,
isNonProd: apiConfig.Value.IsNonProd ?? false,
ImmutableList.Create(apiConfig.Value.ScheduledMaintenances ?? Array.Empty<ScheduledMaintenanceConfiguration>()));
using var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(agentConfig.Value.AgentInterval) };
var sonarClient = new SonarClient(apiConfig, httpClient);
try {
await sonarClient.UpdateEnvironmentAsync(environment.Name, environment, cancellationToken);
} catch (ApiException apiException) when (apiException is { StatusCode: 404 }) {
logger.LogInformation(message: "Environment {environment} does not exist, creating.", environment.Name);
await sonarClient.CreateEnvironmentAsync(environment, cancellationToken);
}
}
}