-
Notifications
You must be signed in to change notification settings - Fork 150
/
ServiceRunner.cs
501 lines (471 loc) · 20.4 KB
/
ServiceRunner.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
using DasMulli.Win32.ServiceUtils;
using System;
using PeterKottas.DotNetCore.WindowsService.Enums;
using System.Diagnostics;
using System.ServiceProcess;
using PeterKottas.DotNetCore.CmdArgParser;
using System.Collections.Generic;
using System.Linq;
using PeterKottas.DotNetCore.WindowsService.Interfaces;
using Microsoft.Extensions.PlatformAbstractions;
using System.IO;
using System.Threading.Tasks;
using PeterKottas.DotNetCore.WindowsService.StateMachines;
namespace PeterKottas.DotNetCore.WindowsService
{
public static class ServiceRunner<SERVICE>
{
public static int Run(Action<HostConfigurator<SERVICE>> runAction)
{
Directory.SetCurrentDirectory(PlatformServices.Default.Application.ApplicationBasePath);
var innerConfig = new HostConfiguration<SERVICE>();
innerConfig.Action = ActionEnum.RunInteractive;
innerConfig.Name = typeof(SERVICE).FullName;
innerConfig.ExtraArguments = Parser.Parse(config =>
{
config.AddParameter(new CmdArgParam()
{
Key = "username",
Description = "Username for the service account",
Value = val =>
{
innerConfig.Username = val;
}
});
config.AddParameter(new CmdArgParam()
{
Key = "password",
Description = "Password for the service account",
Value = val =>
{
innerConfig.Password = val;
}
});
config.AddParameter(new CmdArgParam()
{
Key = "built-in-account",
Description = "Password for the service account",
Value = val =>
{
switch (val.ToLower())
{
case "localsystem":
innerConfig.DefaultCred = Win32ServiceCredentials.LocalSystem;
break;
case "localservice":
innerConfig.DefaultCred = Win32ServiceCredentials.LocalService;
break;
case "networkservice":
innerConfig.DefaultCred = Win32ServiceCredentials.NetworkService;
break;
default:
innerConfig.DefaultCred = Win32ServiceCredentials.LocalSystem;
break;
}
}
});
config.AddParameter(new CmdArgParam()
{
Key = "start-immediately",
Description = "Start the service immediately when installing.",
Value = val =>
{
if (bool.TryParse(val, out var startImmediately))
{
innerConfig.StartImmediately = startImmediately;
}
}
});
config.AddParameter(new CmdArgParam()
{
Key = "name",
Description = "Service name",
Value = val =>
{
innerConfig.Name = val;
}
});
config.AddParameter(new CmdArgParam()
{
Key = "description",
Description = "Service description",
Value = val =>
{
innerConfig.Description = val;
}
});
config.AddParameter(new CmdArgParam()
{
Key = "display-name",
Description = "Service display name",
Value = val =>
{
innerConfig.DisplayName = val;
}
});
config.AddParameter(new CmdArgParam() {
Key = "command",
Description = "Send a custom command to the service.",
Value = val => {
if (int.TryParse(val, out var command)) {
innerConfig.CustomCommand = command;
}
}
});
config.AddParameter(new CmdArgParam()
{
Key = "action",
Description = "Installs the service. It's run like console application otherwise",
Value = val =>
{
switch (val)
{
case "install":
innerConfig.Action = ActionEnum.Install;
break;
case "pause":
innerConfig.Action = ActionEnum.Pause;
break;
case "continue":
innerConfig.Action = ActionEnum.Continue;
break;
case "start":
innerConfig.Action = ActionEnum.Start;
break;
case "stop":
innerConfig.Action = ActionEnum.Stop;
break;
case "uninstall":
innerConfig.Action = ActionEnum.Uninstall;
break;
case "run":
innerConfig.Action = ActionEnum.Run;
break;
case "run-interactive":
innerConfig.Action = ActionEnum.RunInteractive;
break;
case "custom-command":
innerConfig.Action = ActionEnum.CustomCommand;
break;
default:
Console.WriteLine("{0} is unrecognized, will run the app as console application instead");
innerConfig.Action = ActionEnum.RunInteractive;
break;
}
}
});
config.UseDefaultHelp();
config.UseAppDescription("Sample microservice application");
});
if (string.IsNullOrEmpty(innerConfig.Name))
{
innerConfig.Name = typeof(SERVICE).FullName;
}
if (string.IsNullOrEmpty(innerConfig.DisplayName))
{
innerConfig.DisplayName = innerConfig.Name;
}
if (string.IsNullOrEmpty(innerConfig.Description))
{
innerConfig.Description = "No description";
}
var hostConfiguration = new HostConfigurator<SERVICE>(innerConfig);
try
{
runAction(hostConfiguration);
if (innerConfig.Action == ActionEnum.Run)
innerConfig.Service = innerConfig.ServiceFactory(innerConfig.ExtraArguments,
new MicroServiceController(() =>
{
var task = Task.Factory.StartNew(() =>
{
UsingServiceController(innerConfig, (sc, cfg) => StopService(cfg, sc));
});
}
));
else if (innerConfig.Action == ActionEnum.RunInteractive)
{
var consoleService = new InnerService(innerConfig.Name, () => Start(innerConfig), () => Stop(innerConfig), () => Shutdown(innerConfig));
var consoleHost = new ConsoleServiceHost<SERVICE>(consoleService, innerConfig);
innerConfig.Service = innerConfig.ServiceFactory(innerConfig.ExtraArguments,
new MicroServiceController(() =>
{
var task = Task.Factory.StartNew(() =>
{
consoleHost.StopService();
});
}
));
// Return the console host run result, so we get some idea what failed if result is not OK
return (int)consoleHost.Run();
}
else
{
innerConfig.Service = innerConfig.ServiceFactory(innerConfig.ExtraArguments, null);
}
ConfigureService(innerConfig);
return 0;
}
catch (Exception e)
{
Error(innerConfig, e);
return -1;
}
}
private static string GetServiceCommand(List<string> extraArguments)
{
var host = Process.GetCurrentProcess().MainModule.FileName;
if (host.EndsWith("dotnet.exe", StringComparison.OrdinalIgnoreCase))
{
var appPath = Path.Combine(System.AppContext.BaseDirectory,
System.Reflection.Assembly.GetEntryAssembly().GetName().Name + ".dll");
host = string.Format("{0} \"{1}\"", SanitiseArgument(host), appPath);
}
else
{
//For self-contained apps, skip the dll path
extraArguments = extraArguments.Skip(1).ToList();
}
var fullServiceCommand = string.Format("{0} {1} {2}", host, string.Join(" ", extraArguments.Select(arg => SanitiseArgument(arg))), "action:run");
return fullServiceCommand;
}
private static string SanitiseArgument(string arg)
{
if (string.IsNullOrEmpty(arg))
{
return arg;
}
return arg.Contains(" ") ? "\"" + arg + "\"" : arg;
}
private static void Install(HostConfiguration<SERVICE> config, ServiceController sc, int counter = 0)
{
Win32ServiceCredentials cred = config.DefaultCred;
if (!string.IsNullOrEmpty(config.Username))
{
cred = new Win32ServiceCredentials(config.Username, config.Password);
}
try
{
new Win32ServiceManager().CreateService(new ServiceDefinition(config.Name, GetServiceCommand(config.ExtraArguments))
{
DisplayName = config.DisplayName,
Description = config.Description,
Credentials = cred,
AutoStart = true,
DelayedAutoStart = !config.StartImmediately,
ErrorSeverity = ErrorSeverity.Normal
});
Console.WriteLine($@"Successfully registered and started service ""{config.Name}"" (""{config.Description}"")");
config.OnServiceInstall?.Invoke(config.Service);
}
catch (Exception e)
{
if (e.Message.Contains("already exists"))
{
Console.WriteLine($@"Service ""{config.Name}"" (""{config.Description}"") was already installed. Reinstalling...");
Reinstall(config, sc);
}
else if (e.Message.Contains("The specified service has been marked for deletion"))
{
if (counter < 10)
{
System.Threading.Thread.Sleep(500);
counter++;
string suffix = "th";
if (counter == 1)
{
suffix = "st";
}
else if (counter == 2)
{
suffix = "nd";
}
else if (counter == 3)
{
suffix = "rd";
}
Console.WriteLine("The specified service has been marked for deletion. Retrying {0}{1} time", counter, suffix);
Install(config, sc, counter);
}
else
{
throw;
}
}
else
{
throw;
}
}
}
private static void Uninstall(HostConfiguration<SERVICE> config, ServiceController sc)
{
try
{
if (!(sc.Status == ServiceControllerStatus.Stopped || sc.Status == ServiceControllerStatus.StopPending))
{
StopService(config, sc);
}
new Win32ServiceManager().DeleteService(config.Name);
Console.WriteLine($@"Successfully unregistered service ""{config.Name}"" (""{config.Description}"")");
config.OnServiceUnInstall?.Invoke(config.Service);
}
catch (Exception e)
{
if (!e.Message.Contains("does not exist"))
{
throw;
}
Console.WriteLine($@"Service ""{config.Name}"" (""{config.Description}"") does not exist. No action taken.");
}
}
private static void StopService(HostConfiguration<SERVICE> config, ServiceController sc)
{
if (!(sc.Status == ServiceControllerStatus.Stopped | sc.Status == ServiceControllerStatus.StopPending))
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(1000));
Console.WriteLine($@"Successfully stopped service ""{config.Name}"" (""{config.Description}"")");
config.OnServiceStop?.Invoke(config.Service);
}
else
{
Console.WriteLine($@"Service ""{config.Name}"" (""{config.Description}"") is already stopped or stop is pending.");
}
}
private static void PauseService(HostConfiguration<SERVICE> config, ServiceController sc)
{
if (!(sc.Status == ServiceControllerStatus.Paused | sc.Status == ServiceControllerStatus.PausePending))
{
sc.Pause();
sc.WaitForStatus(ServiceControllerStatus.Paused, TimeSpan.FromMilliseconds(1000));
Console.WriteLine($@"Successfully paused service ""{config.Name}"" (""{config.Description}"")");
config.OnServicePause?.Invoke(config.Service);
}
else
{
Console.WriteLine($@"Service ""{config.Name}"" (""{config.Description}"") is already paused or stop is pending.");
}
}
private static void ContinueService(HostConfiguration<SERVICE> config, ServiceController sc)
{
if (!(sc.Status == ServiceControllerStatus.Running | sc.Status == ServiceControllerStatus.ContinuePending))
{
sc.Continue();
sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(1000));
Console.WriteLine($@"Successfully stopped service ""{config.Name}"" (""{config.Description}"")");
config.OnServiceContinue?.Invoke(config.Service);
}
else
{
Console.WriteLine($@"Service ""{config.Name}"" (""{config.Description}"") is already stopped or stop is pending.");
}
}
private static void StartService(HostConfiguration<SERVICE> config, ServiceController sc)
{
if (!(sc.Status == ServiceControllerStatus.StartPending | sc.Status == ServiceControllerStatus.Running))
{
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(1000));
Console.WriteLine($@"Successfully started service ""{config.Name}"" (""{config.Description}"")");
}
else
{
Console.WriteLine($@"Service ""{config.Name}"" (""{config.Description}"") is already running or start is pending.");
}
}
private static void Reinstall(HostConfiguration<SERVICE> config, ServiceController sc)
{
StopService(config, sc);
Uninstall(config, sc);
Install(config, sc);
}
private static void SendCustomCommandToService(HostConfiguration<SERVICE> config, ServiceController sc) {
if (sc.Status == ServiceControllerStatus.Running) {
sc.ExecuteCommand(config.CustomCommand);
Console.WriteLine($@"Successfully sent custom command ({config.CustomCommand}) to service ""{config.Name}"" (""{config.Description}"")");
config.OnServiceCustomCommand(config.Service, config.CustomCommand);
} else {
Console.WriteLine($@"Service ""{config.Name}"" (""{config.Description}"") isn't running so can't send custom command ({config.CustomCommand})");
}
}
private static void ConfigureService(HostConfiguration<SERVICE> config)
{
switch (config.Action)
{
case ActionEnum.Install:
UsingServiceController(config, (sc, cfg) => Install(cfg, sc));
break;
case ActionEnum.Pause:
UsingServiceController(config, (sc, cfg) => PauseService(cfg, sc));
break;
case ActionEnum.Continue:
UsingServiceController(config, (sc, cfg) => ContinueService(cfg, sc));
break;
case ActionEnum.Uninstall:
UsingServiceController(config, (sc, cfg) => Uninstall(cfg, sc));
break;
case ActionEnum.Run:
var testService = new InnerService(config.Name, () => Start(config), () => Stop(config), () => Shutdown(config));
var serviceHost = new Win32ServiceHost(config.Name, new ShutdownableServiceStateMachine(testService));
serviceHost.Run();
break;
case ActionEnum.RunInteractive:
break;
case ActionEnum.Stop:
UsingServiceController(config, (sc, cfg) => StopService(cfg, sc));
break;
case ActionEnum.Start:
UsingServiceController(config, (sc, cfg) => StartService(cfg, sc));
break;
case ActionEnum.CustomCommand:
UsingServiceController(config, (sc, cfg) => SendCustomCommandToService(cfg, sc));
break;
}
}
private static void UsingServiceController(HostConfiguration<SERVICE> config, Action<ServiceController, HostConfiguration<SERVICE>> action)
{
using (var sc = new ServiceController(config.Name))
{
action(sc, config);
}
}
private static void Start(HostConfiguration<SERVICE> config)
{
try
{
config.OnServiceStart(config.Service, config.ExtraArguments);
}
catch (Exception e)
{
Error(config, e);
}
}
private static void Stop(HostConfiguration<SERVICE> config)
{
try
{
config.OnServiceStop(config.Service);
}
catch (Exception e)
{
Error(config, e);
}
}
private static void Shutdown(HostConfiguration<SERVICE> config)
{
try
{
config.OnServiceShutdown(config.Service);
}
catch (Exception e)
{
Error(config, e);
}
}
private static void Error(HostConfiguration<SERVICE> config, Exception e = null)
{
config.OnServiceError(e);
}
}
}