/
AuditIngestion.cs
268 lines (233 loc) · 10.3 KB
/
AuditIngestion.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
namespace ServiceControl.Audit.Auditing
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Infrastructure.Settings;
using Microsoft.Extensions.Hosting;
using NServiceBus;
using NServiceBus.Logging;
using NServiceBus.Transport;
using Persistence;
using Persistence.UnitOfWork;
using ServiceControl.Infrastructure;
using ServiceControl.Infrastructure.Metrics;
using Transports;
class AuditIngestion : IHostedService
{
static readonly long FrequencyInMilliseconds = Stopwatch.Frequency / 1000;
public AuditIngestion(
Settings settings,
ITransportCustomization transportCustomization,
TransportSettings transportSettings,
Metrics metrics,
IFailedAuditStorage failedImportsStorage,
AuditIngestionCustomCheck.State ingestionState,
AuditIngestor auditIngestor,
IAuditIngestionUnitOfWorkFactory unitOfWorkFactory,
IHostApplicationLifetime applicationLifetime)
{
inputEndpoint = settings.AuditQueue;
this.transportCustomization = transportCustomization;
this.transportSettings = transportSettings;
this.auditIngestor = auditIngestor;
this.unitOfWorkFactory = unitOfWorkFactory;
this.settings = settings;
this.applicationLifetime = applicationLifetime;
batchSizeMeter = metrics.GetMeter("Audit ingestion - batch size");
batchDurationMeter = metrics.GetMeter("Audit ingestion - batch processing duration", FrequencyInMilliseconds);
receivedMeter = metrics.GetCounter("Audit ingestion - received");
channel = Channel.CreateBounded<MessageContext>(new BoundedChannelOptions(settings.MaximumConcurrencyLevel)
{
SingleReader = true,
SingleWriter = false,
AllowSynchronousContinuations = false,
FullMode = BoundedChannelFullMode.Wait
});
errorHandlingPolicy = new AuditIngestionFaultPolicy(failedImportsStorage, settings.LoggingSettings, OnCriticalError);
watchdog = new Watchdog("audit message ingestion", EnsureStarted, EnsureStopped, ingestionState.ReportError, ingestionState.Clear, settings.TimeToRestartAuditIngestionAfterFailure, logger);
ingestionWorker = Task.Run(() => Loop(), CancellationToken.None);
}
public Task StartAsync(CancellationToken _) => watchdog.Start(() => applicationLifetime.StopApplication());
public async Task StopAsync(CancellationToken cancellationToken)
{
await watchdog.Stop();
channel.Writer.Complete();
await ingestionWorker;
if (transportInfrastructure != null)
{
await transportInfrastructure.Shutdown(cancellationToken);
}
}
Task OnCriticalError(string failure, Exception exception)
{
logger.Fatal($"OnCriticalError. '{failure}'", exception);
return watchdog.OnFailure(failure);
}
async Task EnsureStarted(CancellationToken cancellationToken = default)
{
try
{
logger.Debug("Ensure started. Start/stop semaphore acquiring");
await startStopSemaphore.WaitAsync(cancellationToken);
logger.Debug("Ensure started. Start/stop semaphore acquired");
if (!unitOfWorkFactory.CanIngestMore())
{
if (queueIngestor != null)
{
var stoppable = queueIngestor;
queueIngestor = null;
logger.Info("Shutting down due to failed persistence health check. Infrastructure shut down commencing");
await stoppable.StopReceive(cancellationToken);
logger.Info("Shutting down due to failed persistence health check. Infrastructure shut down completed");
}
return;
}
if (queueIngestor != null)
{
logger.Debug("Ensure started. Already started, skipping start up");
return; //Already started
}
logger.Info("Ensure started. Infrastructure starting");
transportInfrastructure = await transportCustomization.CreateTransportInfrastructure(
inputEndpoint,
transportSettings,
OnMessage,
errorHandlingPolicy.OnError,
OnCriticalError,
TransportTransactionMode.ReceiveOnly);
queueIngestor = transportInfrastructure.Receivers[inputEndpoint];
await auditIngestor.VerifyCanReachForwardingAddress();
await queueIngestor.StartReceive(cancellationToken);
logger.Info("Ensure started. Infrastructure started");
}
catch
{
if (queueIngestor != null)
{
try
{
await queueIngestor.StopReceive(cancellationToken);
}
catch (OperationCanceledException e) when (e.CancellationToken == cancellationToken)
{
// ignored
}
}
queueIngestor = null; // Setting to null so that it doesn't exit when it retries in line 185
throw;
}
finally
{
logger.Debug("Ensure started. Start/stop semaphore releasing");
startStopSemaphore.Release();
logger.Debug("Ensure started. Start/stop semaphore released");
}
}
async Task EnsureStopped(CancellationToken cancellationToken = default)
{
try
{
logger.Info("Shutting down. Start/stop semaphore acquiring");
await startStopSemaphore.WaitAsync(cancellationToken);
logger.Info("Shutting down. Start/stop semaphore acquired");
if (queueIngestor == null)
{
logger.Info("Shutting down. Already stopped, skipping shut down");
return; //Already stopped
}
var stoppable = queueIngestor;
queueIngestor = null;
logger.Info("Shutting down. Infrastructure shut down commencing");
await stoppable.StopReceive(cancellationToken);
logger.Info("Shutting down. Infrastructure shut down completed");
}
catch (OperationCanceledException e) when (e.CancellationToken == cancellationToken)
{
// ignored
}
finally
{
logger.Info("Shutting down. Start/stop semaphore releasing");
startStopSemaphore.Release();
logger.Info("Shutting down. Start/stop semaphore released");
}
}
async Task OnMessage(MessageContext messageContext, CancellationToken cancellationToken)
{
if (settings.MessageFilter != null && settings.MessageFilter(messageContext))
{
return;
}
var taskCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
messageContext.SetTaskCompletionSource(taskCompletionSource);
receivedMeter.Mark();
await channel.Writer.WriteAsync(messageContext, cancellationToken);
await taskCompletionSource.Task;
}
async Task Loop()
{
var contexts = new List<MessageContext>(settings.MaximumConcurrencyLevel);
while (await channel.Reader.WaitToReadAsync())
{
// will only enter here if there is something to read.
try
{
// as long as there is something to read this will fetch up to MaximumConcurrency items
while (channel.Reader.TryRead(out var context))
{
contexts.Add(context);
}
batchSizeMeter.Mark(contexts.Count);
using (batchDurationMeter.Measure())
{
await auditIngestor.Ingest(contexts);
}
}
catch (OperationCanceledException)
{
//Do nothing as we are shutting down
continue;
}
catch (Exception e) // show must go on
{
if (logger.IsInfoEnabled)
{
logger.Info("Ingesting messages failed", e);
}
// signal all message handling tasks to terminate
foreach (var context in contexts)
{
context.GetTaskCompletionSource().TrySetException(e);
}
}
finally
{
contexts.Clear();
}
}
// will fall out here when writer is completed
}
TransportInfrastructure transportInfrastructure;
IMessageReceiver queueIngestor;
readonly SemaphoreSlim startStopSemaphore = new SemaphoreSlim(1);
readonly string inputEndpoint;
readonly ITransportCustomization transportCustomization;
readonly TransportSettings transportSettings;
readonly AuditIngestor auditIngestor;
readonly AuditIngestionFaultPolicy errorHandlingPolicy;
readonly IAuditIngestionUnitOfWorkFactory unitOfWorkFactory;
readonly Settings settings;
readonly Channel<MessageContext> channel;
readonly Meter batchSizeMeter;
readonly Meter batchDurationMeter;
readonly Counter receivedMeter;
readonly Watchdog watchdog;
readonly Task ingestionWorker;
readonly IHostApplicationLifetime applicationLifetime;
static readonly ILog logger = LogManager.GetLogger<AuditIngestion>();
}
}