-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathServiceControlBaseService.cs
More file actions
438 lines (368 loc) · 15.6 KB
/
ServiceControlBaseService.cs
File metadata and controls
438 lines (368 loc) · 15.6 KB
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
namespace ServiceControlInstaller.Engine.Instances
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading.Tasks;
using Accounts;
using Configuration;
using FileSystem;
using NuGet.Versioning;
using ReportCard;
using Services;
using UrlAcl;
using Validation;
using AppConfig = Configuration.ServiceControl.AppConfig;
public abstract class ServiceControlBaseService : BaseService
{
protected ServiceControlBaseService(IWindowsServiceController service)
{
Service = service;
AppConfig = CreateAppConfig();
}
public bool InMaintenanceMode { get; set; }
public ReportCard ReportCard { get; set; }
/// <summary>
/// Raven management URL
/// </summary>
public string StorageUrl
{
get
{
string host = HostName switch
{
"*" or "+" => "localhost",
_ => HostName,
};
return $"http://{host}:{DatabaseMaintenancePort}/studio/index.html#databases";
}
}
public string AclUrl
{
get
{
var baseUrl = $"http://{HostName}:{Port}/";
if (string.IsNullOrWhiteSpace(VirtualDirectory))
{
return baseUrl;
}
return $"{baseUrl}{VirtualDirectory}{(VirtualDirectory.EndsWith("/") ? string.Empty : "/")}";
}
}
public string AclMaintenanceUrl
{
get
{
//RavenDB when provided with localhost as the hostname will try to open ports on all interfaces
//by using + http binding. This in turn requires a matching UrlAcl registration.
var baseUrl = string.Equals("localhost", HostName, StringComparison.OrdinalIgnoreCase)
? $"http://+:{DatabaseMaintenancePort}/"
: $"http://{HostName}:{DatabaseMaintenancePort}/";
return baseUrl;
}
}
public string LogPath { get; set; }
public string DBPath { get; set; }
public string HostName { get; set; }
public int Port { get; set; }
public int? DatabaseMaintenancePort { get; set; }
public string VirtualDirectory { get; set; }
public string ErrorQueue { get; set; }
public string AuditQueue { get; set; }
public string ErrorLogQueue { get; set; }
public string AuditLogQueue { get; set; }
public bool ForwardAuditMessages { get; set; }
public bool ForwardErrorMessages { get; set; }
public string ConnectionString { get; set; }
public TimeSpan ErrorRetentionPeriod { get; set; }
public bool SkipQueueCreation { get; set; }
public bool EnableFullTextSearchOnBodies { get; set; }
protected abstract string BaseServiceName { get; }
public string Url
{
get
{
if (string.IsNullOrWhiteSpace(VirtualDirectory))
{
return $"http://{HostName}:{Port}/api/";
}
return $"http://{HostName}:{Port}/{VirtualDirectory}{(VirtualDirectory.EndsWith("/") ? string.Empty : "/")}api/";
}
}
public string BrowsableUrl
{
get
{
string host = HostName switch
{
"*" => "localhost",
"+" => Environment.MachineName.ToLower(),
_ => HostName,
};
if (string.IsNullOrWhiteSpace(VirtualDirectory))
{
return $"http://{host}:{Port}/api/";
}
return $"http://{host}:{Port}/{VirtualDirectory}{(VirtualDirectory.EndsWith("/") ? string.Empty : "/")}api/";
}
}
protected string ReadConnectionString()
{
if (File.Exists(Service.ExePath))
{
var configManager = ConfigurationManager.OpenExeConfiguration(Service.ExePath);
var namedConnectionString = configManager.ConnectionStrings.ConnectionStrings["NServiceBus/Transport"];
if (namedConnectionString != null)
{
return namedConnectionString.ConnectionString;
}
}
return null;
}
protected abstract TransportInfo DetermineTransportPackage();
protected void RecreateUrlAcl(ServiceControlBaseService oldSettings)
{
oldSettings.RemoveUrlAcl();
var reservation = new UrlReservation(AclUrl, new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null));
reservation.Create();
if (oldSettings.Version.Major < 2) //Maintenance port was introduced in Version 2
{
return;
}
var maintanceReservation = new UrlReservation(AclMaintenanceUrl, new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null));
maintanceReservation.Create();
}
protected string DefaultDBPath()
{
var host = HostName == "*" ? "%" : HostName;
var dbFolder = $"{host}-{Port}";
if (!string.IsNullOrEmpty(VirtualDirectory))
{
dbFolder += $"-{FileUtils.SanitizeFolderName(VirtualDirectory)}";
}
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Particular", BaseServiceName, dbFolder);
}
protected string DefaultLogPath()
{
// The default Logging folder in ServiceControl uses the env vae"%LocalApplicationData%". Since this is env user specific we'll determine it based on profile path instead.
// This only works for a user that has already logged in, which is fine for existing instances
var userAccountName = UserAccount.ParseAccountName(Service.Account);
var profilePath = userAccountName.RetrieveProfilePath();
if (profilePath == null)
{
return null;
}
return Path.Combine(profilePath, $@"AppData\Local\Particular\{BaseServiceName}\logs");
}
public void RemoveUrlAcl()
{
//This is an old aclurl registration for embedded RavenDB instance that includes the hostname.
//We need that to make sure we can clean-up old registration when removing instances created
//by previous versions of ServiceControl
//pre 4.17 versions of ServiceControl were using hostnames in all cases
var pre417LegacyAclMaintenanceUrl = $"http://{HostName}:{DatabaseMaintenancePort}/";
//pre 4.21 version of ServiceControl were using + in all cases
var pre421LegacyAclMaintenanceUlr = $"http://+:{DatabaseMaintenancePort}";
bool IsServiceControlAclUrl(UrlReservation r) =>
r.Url.StartsWith(AclUrl, StringComparison.OrdinalIgnoreCase) ||
r.Url.StartsWith(AclMaintenanceUrl, StringComparison.OrdinalIgnoreCase) ||
r.Url.StartsWith(pre417LegacyAclMaintenanceUrl, StringComparison.OrdinalIgnoreCase) ||
r.Url.StartsWith(pre421LegacyAclMaintenanceUlr, StringComparison.OrdinalIgnoreCase);
foreach (var urlReservation in UrlReservation.GetAll().Where(IsServiceControlAclUrl))
{
try
{
urlReservation.Delete();
}
catch
{
ReportCard.Warnings.Add($"Failed to remove the URLACL for {Url} - Please remove manually via Netsh.exe");
}
}
}
/// <summary>
/// Returns false if a reboot is required to complete deletion
/// </summary>
/// <returns></returns>
public void RemoveBinFolder()
{
try
{
FileUtils.DeleteDirectory(InstallPath, true, false);
}
catch
{
ReportCard.Warnings.Add($"Could not delete the installation directory '{InstallPath}'. Please remove manually");
}
}
public void RemoveLogsFolder()
{
try
{
FileUtils.DeleteDirectory(LogPath, true, false);
}
catch
{
ReportCard.Warnings.Add($"Could not delete the logs directory '{LogPath}'. Please remove manually");
}
}
public void RemoveDataBaseFolder()
{
//Order by length descending in case they are nested paths
var folders = GetPersistencePathsToCleanUp().ToList();
foreach (var folder in folders.OrderByDescending(p => p.Length))
{
try
{
FileUtils.DeleteDirectory(folder, true, false);
}
catch
{
ReportCard.Warnings.Add($"Could not delete '{folder}'. Please remove manually");
}
}
}
public void ApplyConfigChange()
{
var accountName = string.Equals(ServiceAccount, "LocalSystem", StringComparison.OrdinalIgnoreCase) ? "System" : ServiceAccount;
var oldSettings = InstanceFinder.FindServiceControlInstance(Name);
var fileSystemChanged = !string.Equals(oldSettings.LogPath, LogPath, StringComparison.OrdinalIgnoreCase);
var queueNamesChanged = !(string.Equals(oldSettings.AuditQueue, AuditQueue, StringComparison.OrdinalIgnoreCase)
&& string.Equals(oldSettings.ErrorQueue, ErrorQueue, StringComparison.OrdinalIgnoreCase)
&& string.Equals(oldSettings.AuditLogQueue, AuditLogQueue, StringComparison.OrdinalIgnoreCase)
&& string.Equals(oldSettings.ErrorLogQueue, ErrorLogQueue, StringComparison.OrdinalIgnoreCase)
&& oldSettings.ForwardErrorMessages == ForwardErrorMessages
&& oldSettings.ForwardAuditMessages == ForwardAuditMessages);
RecreateUrlAcl(oldSettings);
if (fileSystemChanged)
{
var account = new NTAccount(accountName);
var modifyAccessRule = new FileSystemAccessRule(account, FileSystemRights.Modify | FileSystemRights.Traverse | FileSystemRights.ListDirectory, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
FileUtils.CreateDirectoryAndSetAcl(LogPath, modifyAccessRule);
}
Service.Description = Description;
var configuration = ConfigurationManager.OpenExeConfiguration(Service.ExePath);
var settings = configuration.AppSettings.Settings;
ApplySettingsChanges(settings);
configuration.ConnectionStrings.ConnectionStrings.Set("NServiceBus/Transport", ConnectionString);
configuration.Save();
var passwordSet = !string.IsNullOrWhiteSpace(ServiceAccountPwd);
var accountChanged = !string.Equals(oldSettings.ServiceAccount, ServiceAccount, StringComparison.OrdinalIgnoreCase);
var connectionStringChanged = !string.Equals(ConnectionString, oldSettings.ConnectionString, StringComparison.Ordinal);
//have to save config prior to creating queues (if needed)
if (queueNamesChanged || accountChanged || connectionStringChanged)
{
SetupInstance();
}
if (passwordSet || accountChanged)
{
Service.ChangeAccountDetails(accountName, ServiceAccountPwd);
}
}
protected abstract void ApplySettingsChanges(KeyValueConfigurationCollection settings);
protected abstract AppConfig CreateAppConfig();
public virtual void EnableMaintenanceMode()
{
AppConfig = CreateAppConfig();
AppConfig.EnableMaintenanceMode();
InMaintenanceMode = true;
}
public virtual void DisableMaintenanceMode()
{
AppConfig = CreateAppConfig();
AppConfig.DisableMaintenanceMode();
InMaintenanceMode = false;
}
protected virtual IEnumerable<string> GetPersistencePathsToCleanUp()
{
return [];
}
protected virtual void ValidateConnectionString()
{
}
protected virtual Task ValidatePaths() => Task.CompletedTask;
protected virtual void ValidateQueueNames()
{
}
protected virtual void ValidateServiceAccount()
{
var oldSettings = InstanceFinder.FindServiceControlInstance(Name);
var passwordSet = !string.IsNullOrWhiteSpace(ServiceAccountPwd);
var accountChanged = !string.Equals(oldSettings.ServiceAccount, ServiceAccount, StringComparison.OrdinalIgnoreCase);
if (passwordSet || accountChanged)
{
try
{
ServiceAccountValidation.Validate(this);
}
catch (IdentityNotMappedException)
{
ReportCard.Errors.Add("The service account specified does not exist");
return;
}
catch (EngineValidationException ex)
{
ReportCard.Errors.Add(ex.Message);
return;
}
}
}
public void RestoreAppConfig(string sourcePath)
{
if (sourcePath == null)
{
return;
}
var configFile = $"{Service.ExePath}.config";
File.Copy(sourcePath, configFile, true);
// Populate the config with common settings even if they are defaults
// Will not clobber other settings in the config
AppConfig = CreateAppConfig();
AppConfig.Save();
}
public abstract void RunSetup();
public void SetupInstance()
{
try
{
RunSetup();
}
catch (Exception ex)
{
ReportCard.Errors.Add(ex.Message);
}
}
public async Task ValidateChanges()
{
await ValidatePaths().ConfigureAwait(false);
ValidateQueueNames();
ValidateServiceAccount();
ValidateConnectionString();
}
public void UpgradeTransportSeam()
{
TransportPackage = ServiceControlCoreTransports.UpgradedTransportSeam(TransportPackage);
AppConfig.SetTransportType(TransportPackage.Name);
AppConfig.Save();
}
public void CreateDatabaseBackup()
{
try
{
Directory.Move(DBPath, DatabaseBackupPath);
}
catch (Exception e)
{
throw new Exception($"Could not move {DBPath} to {DatabaseBackupPath}", e);
}
}
public AppConfig AppConfig;
public bool VersionHasServiceControlAuditFeatures => Version >= AuditFeatureMinVersion;
public string DatabaseBackupPath => DBPath + "_UpgradeBackup";
static SemanticVersion AuditFeatureMinVersion = new(4, 0, 0);
}
}