-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathMonitoringInstance.cs
More file actions
293 lines (252 loc) · 10.1 KB
/
MonitoringInstance.cs
File metadata and controls
293 lines (252 loc) · 10.1 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
namespace ServiceControlInstaller.Engine.Instances
{
using System;
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 Configuration.Monitoring;
using FileSystem;
using ReportCard;
using Services;
using Setup;
using UrlAcl;
using Validation;
public class MonitoringInstance : BaseService, IMonitoringInstance
{
public MonitoringInstance(WindowsServiceController service)
{
Service = service;
AppConfig = new AppConfig(this);
Reload();
}
public AppConfig AppConfig { get; set; }
public ReportCard ReportCard { get; set; }
public int Port { get; set; }
public string HostName { get; set; }
public string ErrorQueue { get; set; }
public string ConnectionString { get; set; }
public string LogPath { get; set; }
public bool SkipQueueCreation { get; set; }
public string Url => $"http://{HostName}:{Port}/";
public string BrowsableUrl
{
get
{
string host = HostName switch
{
"*" => "localhost",
"+" => Environment.MachineName.ToLower(),
_ => HostName,
};
return $"http://{host}:{Port}/";
}
}
public override void Reload()
{
Service.Refresh();
AppConfig = new AppConfig(this);
InstanceName = AppConfig.Read(SettingsList.InstanceName, Name);
HostName = AppConfig.Read(SettingsList.HostName, "localhost");
Port = AppConfig.Read(SettingsList.Port, 1234);
LogPath = AppConfig.Read(SettingsList.LogPath, DefaultLogPath());
ErrorQueue = AppConfig.Read(SettingsList.ErrorQueue, "error");
TransportPackage = DetermineTransportPackage();
ConnectionString = ReadConnectionString();
Description = GetDescription();
ServiceAccount = Service.Account;
}
string DefaultLogPath()
{
var userAccountName = UserAccount.ParseAccountName(Service.Account);
var profilePath = userAccountName.RetrieveProfilePath();
if (profilePath == null)
{
return null;
}
return Path.Combine(profilePath, $@"AppData\Local\Particular\{Name}\logs");
}
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;
}
TransportInfo DetermineTransportPackage()
{
var transportAppSetting = (AppConfig.Read<string>(SettingsList.TransportType, null)?.Trim())
?? throw new Exception($"{SettingsList.TransportType.Name} setting not found in app.config.");
var transport = ServiceControlCoreTransports.Find(transportAppSetting);
return transport ?? throw new Exception($"{SettingsList.TransportType.Name} value of '{transportAppSetting}' in app.config is invalid.");
}
public async Task ValidateChanges()
{
try
{
await new PathsValidator(this).RunValidation(false);
}
catch (EngineValidationException ex)
{
ReportCard.Errors.Add(ex.Message);
}
var oldSettings = InstanceFinder.FindMonitoringInstance(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;
}
}
try
{
ConnectionStringValidator.Validate(this);
}
catch (EngineValidationException ex)
{
ReportCard.Errors.Add(ex.Message);
}
}
public void ApplyConfigChange()
{
var accountName = string.Equals(ServiceAccount, "LocalSystem", StringComparison.OrdinalIgnoreCase) ? "System" : ServiceAccount;
var oldSettings = InstanceFinder.FindMonitoringInstance(Name);
var fileSystemChanged = !string.Equals(oldSettings.LogPath, LogPath, StringComparison.OrdinalIgnoreCase);
var queueNamesChanged = !string.Equals(oldSettings.ErrorQueue, ErrorQueue, StringComparison.OrdinalIgnoreCase);
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;
settings.Set(SettingsList.HostName, HostName);
settings.Set(SettingsList.Port, Port.ToString());
settings.Set(SettingsList.LogPath, LogPath);
settings.Set(SettingsList.ErrorQueue, ErrorQueue);
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)
{
try
{
InstanceSetup.Run(this);
}
catch (Exception ex)
{
ReportCard.Errors.Add(ex.Message);
}
}
if (passwordSet || accountChanged)
{
Service.ChangeAccountDetails(accountName, ServiceAccountPwd);
}
}
void RecreateUrlAcl(MonitoringInstance oldSettings)
{
oldSettings.RemoveUrlAcl();
var reservation = new UrlReservation(Url, new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null));
reservation.Create();
}
public void RemoveUrlAcl()
{
foreach (var urlReservation in UrlReservation.GetAll().Where(p => p.Url.StartsWith(Url, StringComparison.OrdinalIgnoreCase)))
{
try
{
urlReservation.Delete();
}
catch
{
ReportCard.Warnings.Add($"Failed to remove the URLACL for {Url} - Please remove manually via Netsh.exe");
}
}
}
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");
}
}
protected override void Prepare(string zipFilePath, string destDir)
{
FileUtils.CloneDirectory(InstallPath, destDir, "license", $"{Constants.MonitoringExe}.config");
FileUtils.UnzipToSubdirectory(zipFilePath, destDir);
FileUtils.UnzipToSubdirectory("InstanceShared.zip", destDir);
}
public void RestoreAppConfig(string sourcePath)
{
if (sourcePath == null)
{
return;
}
File.Copy(sourcePath, $"{Service.ExePath}.config", true);
// Populate the config with common settings even if they are defaults
// Will not clobber other settings in the config
AppConfig = new AppConfig(this);
AppConfig.Save();
}
public void SetupInstance()
{
try
{
InstanceSetup.Run(this);
}
catch (Exception ex)
{
ReportCard.Errors.Add(ex.Message);
}
}
public void UpgradeTransportSeam()
{
TransportPackage = ServiceControlCoreTransports.UpgradedTransportSeam(TransportPackage);
var config = new AppConfig(this);
config.Save();
}
}
}