/
Settings.cs
428 lines (349 loc) · 16.1 KB
/
Settings.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
namespace ServiceBus.Management.Infrastructure.Settings
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using NLog.Common;
using NServiceBus.Logging;
using NServiceBus.Transport;
using ServiceControl.Configuration;
using ServiceControl.Infrastructure.Settings;
using ServiceControl.Infrastructure.WebApi;
using ServiceControl.Persistence;
using ServiceControl.Transports;
using JsonSerializer = System.Text.Json.JsonSerializer;
public class Settings
{
public Settings(
string serviceName = null,
string transportType = null,
string persisterType = null,
bool? forwardErrorMessages = default,
TimeSpan? errorRetentionPeriod = default
)
{
ServiceName = serviceName;
if (string.IsNullOrEmpty(serviceName))
{
ServiceName = DEFAULT_SERVICE_NAME;
}
// Overwrite the service name if it is specified in ENVVAR, reg, or config file
ServiceName = SettingsReader.Read(SettingsRootNamespace, "InternalQueueName", ServiceName);
LoadErrorIngestionSettings();
TryLoadLicenseFromConfig();
TransportConnectionString = GetConnectionString();
TransportType = transportType ?? SettingsReader.Read<string>(SettingsRootNamespace, "TransportType");
PersistenceType = persisterType ?? SettingsReader.Read<string>(SettingsRootNamespace, "PersistenceType");
AuditRetentionPeriod = GetAuditRetentionPeriod();
ForwardErrorMessages = forwardErrorMessages ?? GetForwardErrorMessages();
ErrorRetentionPeriod = errorRetentionPeriod ?? GetErrorRetentionPeriod();
EventsRetentionPeriod = GetEventRetentionPeriod();
Port = SettingsReader.Read(SettingsRootNamespace, "Port", 33333);
ProcessRetryBatchesFrequency = TimeSpan.FromSeconds(30);
MaximumConcurrencyLevel = SettingsReader.Read(SettingsRootNamespace, "MaximumConcurrencyLevel", 10);
RetryHistoryDepth = SettingsReader.Read(SettingsRootNamespace, "RetryHistoryDepth", 10);
AllowMessageEditing = SettingsReader.Read<bool>(SettingsRootNamespace, "AllowMessageEditing");
NotificationsFilter = SettingsReader.Read<string>(SettingsRootNamespace, "NotificationsFilter");
RemoteInstances = GetRemoteInstances().ToArray();
DataSpaceRemainingThreshold = GetDataSpaceRemainingThreshold();
TimeToRestartErrorIngestionAfterFailure = GetTimeToRestartErrorIngestionAfterFailure();
DisableExternalIntegrationsPublishing = SettingsReader.Read(SettingsRootNamespace, "DisableExternalIntegrationsPublishing", false);
}
public string NotificationsFilter { get; set; }
public bool AllowMessageEditing { get; set; }
//HINT: acceptance tests only
public Func<MessageContext, bool> MessageFilter { get; set; }
//HINT: acceptance tests only
public string EmailDropFolder { get; set; }
public bool ValidateConfiguration => SettingsReader.Read(SettingsRootNamespace, "ValidateConfig", true);
public int ExternalIntegrationsDispatchingBatchSize => SettingsReader.Read(SettingsRootNamespace, "ExternalIntegrationsDispatchingBatchSize", 100);
public bool DisableExternalIntegrationsPublishing { get; set; }
public bool SkipQueueCreation { get; set; }
public bool RunCleanupBundle { get; set; }
public string RootUrl
{
get
{
var suffix = string.Empty;
if (!string.IsNullOrEmpty(VirtualDirectory))
{
suffix = $"{VirtualDirectory}/";
}
return $"http://{Hostname}:{Port}/{suffix}";
}
}
public string ApiUrl => $"{RootUrl}api";
string _instanceId;
public string InstanceId
{
get
{
if (string.IsNullOrEmpty(_instanceId))
{
_instanceId = InstanceIdGenerator.FromApiUrl(ApiUrl);
}
return _instanceId;
}
}
public string StorageUrl => $"{RootUrl}storage";
public string StagingQueue => $"{ServiceName}.staging";
public int Port { get; set; }
public string LicenseFileText { get; set; }
public PersistenceSettings PersisterSpecificSettings { get; set; }
public bool PrintMetrics => SettingsReader.Read<bool>(SettingsRootNamespace, "PrintMetrics");
public string Hostname => SettingsReader.Read(SettingsRootNamespace, "Hostname", "localhost");
public string VirtualDirectory => SettingsReader.Read(SettingsRootNamespace, "VirtualDirectory", string.Empty);
public TimeSpan HeartbeatGracePeriod
{
get
{
try
{
return TimeSpan.Parse(SettingsReader.Read(SettingsRootNamespace, "HeartbeatGracePeriod", "00:00:40"));
}
catch (Exception ex)
{
logger.Error($"HeartbeatGracePeriod settings invalid - {ex}. Defaulting HeartbeatGracePeriod to '00:00:40'");
return TimeSpan.FromSeconds(40);
}
}
}
public string TransportType { get; set; }
public string PersistenceType { get; private set; }
public string ErrorLogQueue { get; set; }
public string ErrorQueue { get; set; }
public bool ForwardErrorMessages { get; set; }
public bool IngestErrorMessages { get; set; } = true;
public bool RunRetryProcessor { get; set; } = true;
public TimeSpan? AuditRetentionPeriod { get; set; }
public TimeSpan ErrorRetentionPeriod { get; }
public TimeSpan EventsRetentionPeriod { get; }
public string ServiceName { get; }
public string TransportConnectionString { get; set; }
public TimeSpan ProcessRetryBatchesFrequency { get; set; }
public TimeSpan TimeToRestartErrorIngestionAfterFailure { get; set; }
public int MaximumConcurrencyLevel { get; set; }
public int RetryHistoryDepth { get; set; }
public RemoteInstanceSetting[] RemoteInstances { get; set; }
public int DataSpaceRemainingThreshold { get; set; }
public bool DisableHealthChecks { get; set; }
public ITransportCustomization LoadTransportCustomization()
{
try
{
TransportType = TransportManifestLibrary.Find(TransportType);
var customizationType = Type.GetType(TransportType, true);
return (ITransportCustomization)Activator.CreateInstance(customizationType);
}
catch (Exception e)
{
throw new Exception($"Could not load transport customization type {TransportType}.", e);
}
}
public string GetConnectionString()
{
var settingsValue = SettingsReader.Read<string>(SettingsRootNamespace, "ConnectionString");
if (settingsValue != null)
{
return settingsValue;
}
var connectionStringSettings = ConfigurationManager.ConnectionStrings["NServiceBus/Transport"];
return connectionStringSettings?.ConnectionString;
}
static bool GetForwardErrorMessages()
{
var forwardErrorMessages = SettingsReader.Read<bool?>(SettingsRootNamespace, "ForwardErrorMessages");
if (forwardErrorMessages.HasValue)
{
return forwardErrorMessages.Value;
}
throw new Exception("ForwardErrorMessages settings is missing, please make sure it is included.");
}
TimeSpan GetEventRetentionPeriod()
{
var valueRead = SettingsReader.Read<string>(SettingsRootNamespace, "EventRetentionPeriod");
if (valueRead != null)
{
if (TimeSpan.TryParse(valueRead, out var result))
{
string message;
if (ValidateConfiguration && result < TimeSpan.FromHours(1))
{
message = "EventRetentionPeriod settings is invalid, value should be minimum 1 hour.";
logger.Fatal(message);
throw new Exception(message);
}
if (ValidateConfiguration && result > TimeSpan.FromDays(200))
{
message = "EventRetentionPeriod settings is invalid, value should be maximum 200 days.";
logger.Fatal(message);
throw new Exception(message);
}
return result;
}
}
return TimeSpan.FromDays(14);
}
TimeSpan GetErrorRetentionPeriod()
{
string message;
var valueRead = SettingsReader.Read<string>(SettingsRootNamespace, "ErrorRetentionPeriod");
if (valueRead == null)
{
message = "ErrorRetentionPeriod settings is missing, please make sure it is included.";
logger.Fatal(message);
throw new Exception(message);
}
if (TimeSpan.TryParse(valueRead, out var result))
{
if (ValidateConfiguration && result < TimeSpan.FromDays(5))
{
message = "ErrorRetentionPeriod settings is invalid, value should be minimum 5 days.";
logger.Fatal(message);
throw new Exception(message);
}
if (ValidateConfiguration && result > TimeSpan.FromDays(45))
{
message = "ErrorRetentionPeriod settings is invalid, value should be maximum 45 days.";
logger.Fatal(message);
throw new Exception(message);
}
}
else
{
message = "ErrorRetentionPeriod settings is invalid, please make sure it is a TimeSpan.";
logger.Fatal(message);
throw new Exception(message);
}
return result;
}
TimeSpan? GetAuditRetentionPeriod()
{
string message;
var valueRead = SettingsReader.Read<string>(SettingsRootNamespace, "AuditRetentionPeriod");
if (valueRead == null)
{
return null;
}
if (TimeSpan.TryParse(valueRead, out var result))
{
if (ValidateConfiguration && result < TimeSpan.FromHours(1))
{
message = "AuditRetentionPeriod settings is invalid, value should be minimum 1 hour.";
InternalLogger.Fatal(message);
throw new Exception(message);
}
if (ValidateConfiguration && result > TimeSpan.FromDays(365))
{
message = "AuditRetentionPeriod settings is invalid, value should be maximum 365 days.";
InternalLogger.Fatal(message);
throw new Exception(message);
}
}
else
{
message = "AuditRetentionPeriod settings is invalid, please make sure it is a TimeSpan.";
InternalLogger.Fatal(message);
throw new Exception(message);
}
return result;
}
TimeSpan GetTimeToRestartErrorIngestionAfterFailure()
{
string message;
var valueRead = SettingsReader.Read<string>(SettingsRootNamespace, "TimeToRestartErrorIngestionAfterFailure");
if (valueRead == null)
{
return TimeSpan.FromSeconds(60);
}
if (TimeSpan.TryParse(valueRead, out var result))
{
if (ValidateConfiguration && result < TimeSpan.FromSeconds(5))
{
message = "TimeToRestartErrorIngestionAfterFailure setting is invalid, value should be minimum 5 seconds.";
InternalLogger.Fatal(message);
throw new Exception(message);
}
if (ValidateConfiguration && result > TimeSpan.FromHours(1))
{
message = "TimeToRestartErrorIngestionAfterFailure setting is invalid, value should be maximum 1 hour.";
InternalLogger.Fatal(message);
throw new Exception(message);
}
}
else
{
message = "TimeToRestartErrorIngestionAfterFailure setting is invalid, please make sure it is a TimeSpan.";
InternalLogger.Fatal(message);
throw new Exception(message);
}
return result;
}
static IList<RemoteInstanceSetting> GetRemoteInstances()
{
var valueRead = SettingsReader.Read<string>(SettingsRootNamespace, "RemoteInstances");
if (!string.IsNullOrEmpty(valueRead))
{
return ParseRemoteInstances(valueRead);
}
return Array.Empty<RemoteInstanceSetting>();
}
internal static RemoteInstanceSetting[] ParseRemoteInstances(string value) =>
JsonSerializer.Deserialize<RemoteInstanceSetting[]>(value, SerializerOptions.Default) ?? [];
static string Subscope(string address)
{
var atIndex = address.IndexOf("@", StringComparison.InvariantCulture);
if (atIndex <= -1)
{
return $"{address}.log";
}
var queue = address.Substring(0, atIndex);
var machine = address.Substring(atIndex + 1);
return $"{queue}.log@{machine}";
}
int GetDataSpaceRemainingThreshold()
{
string message;
var threshold = SettingsReader.Read(SettingsRootNamespace, "DataSpaceRemainingThreshold", DataSpaceRemainingThresholdDefault);
if (threshold < 0)
{
message = $"{nameof(DataSpaceRemainingThreshold)} is invalid, minimum value is 0.";
logger.Fatal(message);
throw new Exception(message);
}
if (threshold > 100)
{
message = $"{nameof(DataSpaceRemainingThreshold)} is invalid, maximum value is 100.";
logger.Fatal(message);
throw new Exception(message);
}
return threshold;
}
void LoadErrorIngestionSettings()
{
var serviceBusRootNamespace = new SettingsRootNamespace("ServiceBus");
ErrorQueue = SettingsReader.Read(serviceBusRootNamespace, "ErrorQueue", "error");
if (string.IsNullOrEmpty(ErrorQueue))
{
throw new Exception("ServiceBus/ErrorQueue requires a value to start the instance");
}
IngestErrorMessages = SettingsReader.Read(SettingsRootNamespace, "IngestErrorMessages", true);
if (!IngestErrorMessages)
{
logger.Info("Error ingestion disabled.");
}
ErrorLogQueue = SettingsReader.Read<string>(serviceBusRootNamespace, "ErrorLogQueue", null);
if (ErrorLogQueue == null)
{
logger.Info("No settings found for error log queue to import, default name will be used");
ErrorLogQueue = Subscope(ErrorQueue);
}
}
void TryLoadLicenseFromConfig() => LicenseFileText = SettingsReader.Read<string>(SettingsRootNamespace, "LicenseText");
static readonly ILog logger = LogManager.GetLogger(typeof(Settings));
public const string DEFAULT_SERVICE_NAME = "Particular.ServiceControl";
public static readonly SettingsRootNamespace SettingsRootNamespace = new("ServiceControl");
const int DataSpaceRemainingThresholdDefault = 20;
}
}