-
Notifications
You must be signed in to change notification settings - Fork 32
/
TestWindowsServiceUtil.cs
922 lines (825 loc) · 30 KB
/
TestWindowsServiceUtil.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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Threading;
using NUnit.Framework;
using NExpect;
using PeanutButter.FileSystem;
using PeanutButter.Utils;
using PeanutButter.WindowsServiceManagement.Exceptions;
using static NExpect.Expectations;
using static PeanutButter.RandomGenerators.RandomValueGen;
// ReSharper disable AssignNullToNotNullAttribute
namespace PeanutButter.WindowsServiceManagement.Tests
{
[TestFixture]
public class TestWindowsServiceUtil
{
[Test]
[Explicit("Relies on local installation of mysql 5.7")]
public void ServiceExeShouldReturnServiceExe()
{
// Arrange
var service = new WindowsServiceUtil("MYSQL57");
// Act
var result = service.Commandline;
// Assert
}
[Test]
[Explicit("Run manually on known services")]
public void ACCEPT_WhenTestingStartupStateOfKnownServices_ShouldReturnExpectedState()
{
//---------------Set up test pack-------------------
//---------------Assert Precondition----------------
//---------------Execute Test ----------------------
var svc1 = new WindowsServiceUtil("mssqlserver");
Expect(svc1.StartupType)
.To.Equal(ServiceStartupTypes.Automatic);
var svc2 = new WindowsServiceUtil("gupdatem");
Expect(svc2.StartupType)
.To.Equal(ServiceStartupTypes.Manual);
//---------------Test Result -----------------------
}
[Test]
public void ShouldNotBorkWhenNoService()
{
//---------------Set up test pack-------------------
//---------------Assert Precondition----------------
var svc = new WindowsServiceUtil(GetRandomString(20, 30));
//---------------Execute Test ----------------------
Expect(svc.IsInstalled)
.To.Be.False();
//---------------Test Result -----------------------
}
[Test]
[Explicit("manually testing some stuff")]
public void InstallThing()
{
//---------------Set up test pack-------------------
var localPath = TestServicePath;
//---------------Assert Precondition----------------
Expect(localPath)
.To.Exist($"Expected to find test service at {localPath}");
//---------------Execute Test ----------------------
Run(localPath, "-i");
var util = new WindowsServiceUtil("test service");
Expect(util.IsInstalled).To.Be.True();
// check that we can uninstall
util.Uninstall(true);
Expect(util.IsInstalled)
.To.Be.False();
// check that attempting again throws
Expect(() => util.Uninstall(true))
.To.Throw<ServiceNotInstalledException>();
//---------------Test Result -----------------------
}
[Test]
[Explicit("Run manually, may be system-specific")]
public void ServiceExe_ShouldReturnPathTo()
{
//---------------Set up test pack-------------------
var util = new WindowsServiceUtil("Themes");
//---------------Assert Precondition----------------
Expect(util.IsInstalled)
.To.Be.True();
//---------------Execute Test ----------------------
var path = util.Commandline;
//---------------Test Result -----------------------
Expect(
path?.ToLowerInvariant()
).To.Equal("c:\\windows\\system32\\svchost.exe -k netsvcs");
}
[TestCase("-m")]
[TestCase("--manual-start")]
public void ShouldBeAbleToInstallServiceAsManualStart(string arg)
{
// Arrange
var serviceExe = TestServicePath;
Expect(serviceExe)
.To.Exist($"Expected to find test service at {serviceExe}");
EnsureTestServiceIsNotInstalled();
// Act
Do("Install via cli: manual start",
() => Run(serviceExe, "-i", arg, "-n", TestServiceName)
);
var util = new WindowsServiceUtil(TestServiceName);
// Assert
Expect(util.StartupType)
.To.Equal(ServiceStartupTypes.Manual);
Expect(util.State)
.To.Equal(ServiceState.Stopped);
}
[Test]
public void ShouldBeAbleToInstallServiceAsManualStartViaApi()
{
// Arrange
var serviceExe = TestServicePath;
Expect(serviceExe)
.To.Exist($"Expected to find test service at {serviceExe}");
EnsureTestServiceIsNotInstalled();
var sut = Create(TestServiceName, TestServiceName, serviceExe);
// Act
sut.Install(ServiceBootFlag.ManualStart);
// Assert
var util = Create(TestServiceName);
Expect(util.StartupType)
.To.Equal(ServiceStartupTypes.Manual);
Expect(util.State)
.To.Equal(ServiceState.Stopped);
}
[TestCase("-z")]
[TestCase("--disabled")]
public void ShouldBeAbleToInstallServiceAsDisabled(string arg)
{
// Arrange
var serviceExe = TestServicePath;
Expect(serviceExe)
.To.Exist($"Expected to find test service at {serviceExe}");
EnsureTestServiceIsNotInstalled();
// Act
Do("Install via cli: manual start",
() => Run(serviceExe, "-i", arg, "-n", TestServiceName)
);
var util = new WindowsServiceUtil(TestServiceName);
// Assert
Expect(util.StartupType)
.To.Equal(ServiceStartupTypes.Disabled);
}
[Test]
public void BigHairyIntegrationTest()
{
if (Platform.Is32Bit)
{
Assert.Ignore(
"Running 32-bit: test will fail: 32-bit process cannot access 64-bit process info"
);
}
// Arrange
var serviceExe = TestServicePath;
Expect(serviceExe).To.Exist($"Expected to find test service at {serviceExe}");
EnsureTestServiceIsNotInstalled();
// Act
Do("Install via cli", () => Run(serviceExe, "-i", "-n", TestServiceName));
var util = new WindowsServiceUtil(TestServiceName);
Do("Test is installed",
() => Expect(util.IsInstalled)
.To.Be.True()
);
Do("Test service commandline",
() => Expect(util.Commandline)
.To.Equal(serviceExe)
);
Do("Test default startup type",
() => Expect(util.StartupType)
.To.Equal(ServiceStartupTypes.Automatic)
);
Do("Disabled service",
() =>
{
util.Disable();
Expect(util.StartupType)
.To.Equal(ServiceStartupTypes.Disabled);
});
Do("Re-enable service",
() =>
{
util.SetAutomaticStart();
Expect(util.StartupType)
.To.Equal(ServiceStartupTypes.Automatic);
});
Do("Start service",
() =>
{
util.Start();
Expect(util.State)
.To.Equal(ServiceState.Running);
var processes = Process.GetProcesses();
var process = processes.FirstOrDefault(p =>
{
try
{
return p?.MainModule?.FileName.Equals(serviceExe, StringComparison.OrdinalIgnoreCase) ??
false;
}
catch
{
return false;
}
});
Expect(process).Not.To.Be.Null(
() =>
$"@Service should be running: {serviceExe}\nrunning:\n{DumpProcesses()}"
);
Expect(process.Id)
.To.Equal(util.ServicePID);
string DumpProcesses()
{
return processes.Select(p =>
{
try
{
return $"{p.MainModule.FileName}";
}
catch (Exception e)
{
return $"(unknown) ({e.Message})";
}
}).OrderBy(s => s).JoinWith("\n");
;
}
});
var byPath = WindowsServiceUtil.GetServiceByPath(serviceExe);
Expect(byPath)
.Not.To.Be.Null($"Should be able to query service by path {serviceExe}");
Do("Pause service",
() =>
{
byPath.Pause();
Expect(byPath.State)
.To.Equal(ServiceState.Paused);
});
Do("Resume service",
() =>
{
byPath.Continue();
Expect(byPath.State)
.To.Equal(ServiceState.Running);
});
Do("Stop service",
() =>
{
util.Stop();
Expect(util.State)
.To.Equal(ServiceState.Stopped);
});
Do("Uninstall via cli",
() =>
{
Run(serviceExe, "-u", "-n", TestServiceName);
Expect(util.IsInstalled)
.To.Be.False();
});
Do("Install and start (api)",
() =>
{
util = new WindowsServiceUtil(
TestServiceName,
TestServiceName,
serviceExe);
util.InstallAndStart();
Expect(util.IsInstalled)
.To.Be.True();
Expect(util.State)
.To.Equal(ServiceState.Running);
});
Do("Re-install and start (api)",
() =>
{
util = new WindowsServiceUtil(
TestServiceName,
TestServiceName,
serviceExe);
util.Uninstall();
util.InstallAndStart();
Expect(util.IsInstalled)
.To.Be.True();
Expect(util.State)
.To.Equal(ServiceState.Running);
});
Do("Uninstall (api)", () => util.Uninstall());
// Assert
}
[TestFixture]
public class KillService : TestWindowsServiceUtil
{
[Test]
[Explicit("Slow and flaky")]
public void ShouldKillSingleWithoutArgs()
{
// Arrange
var util = Create(
TestServiceName,
TestServiceName,
TestServicePath
);
util.InstallAndStart();
// Act
var allProcesses = Process.GetProcesses();
var proc = allProcesses
.Single(p => HasMainModule(p, TestServicePath));
var result = util.KillService();
// Assert
Expect(proc.HasExited)
.To.Be.True();
Expect(result)
.To.Equal(KillServiceResult.Killed);
}
private static bool HasMainModule(
Process p,
string path)
{
try
{
return p.MainModule.FileName == path;
}
catch // easy to get access denied!
{
return false;
}
}
// Spaced Service doesn't attempt to do anything with arguments, so it's
// nice for testing this out
[Test]
[Explicit("Slow and flaky")]
public void ShouldKillTheCorrectService()
{
// Arrange
var service1Name = $"service-1-{Guid.NewGuid()}";
var service2Name = $"service-2-{Guid.NewGuid()}";
var args1 = GetRandomArray<string>(2);
var args2 = GetRandomArray<string>(2);
var cli1 = $"\"{SpacedServiceExe}\" {string.Join(" ", args1)}";
var cli2 = $"\"{SpacedServiceExe}\" {string.Join(" ", args2)}";
var util1 = Create(service1Name, service1Name, cli1);
var util2 = Create(service2Name, service2Name, cli2);
util1.InstallAndStart();
util2.InstallAndStart();
using var _ = new AutoResetter(Noop, () =>
{
TryDo(() => util1.Uninstall());
TryDo(() => util2.Uninstall());
});
var processes = Process.GetProcesses()
.Where(p => HasMainModule(p, SpacedServiceExe))
.ToArray();
var p1 = processes.FirstOrDefault(
p =>
{
var testArgs = p.QueryCommandline()
.SplitCommandline()
.Skip(1)
.ToArray();
return testArgs.Matches(args1);
}
);
var p2 = processes.FirstOrDefault(
p => p.QueryCommandline()
.SplitCommandline()
.Skip(1)
.Matches(args2)
);
Expect(p1)
.Not.To.Be.Null(() => $"Can't find process for {cli1}");
Expect(p2)
.Not.To.Be.Null(() => $"Can't find process for {cli2}");
// Act
util1.KillService();
// Assert
Expect(p1.HasExited)
.To.Be.True();
Expect(p2.HasExited)
.To.Be.False();
}
}
[TestFixture]
public class StubbornService
{
[Test]
public void ShouldBeAbleToSuccessfullyUninstallWithForceOption()
{
// by definition, if this fails, it may require manual cleanup
// -> stubborn-service will basically lock for a minute
// when requested to stop
// Arrange
var serviceExe = StubbornServiceExe;
var serviceName = $"stubborn-service-{Guid.NewGuid()}";
var util = Create(
serviceName,
serviceName,
serviceExe);
// Act
util.InstallAndStart();
var servicePid = util.ServicePID;
util.Uninstall(
ControlOptions.Wait |
ControlOptions.Force
);
// Assert
Expect(() => Process.GetProcessById(servicePid))
.To.Throw<ArgumentException>(); // shouldn't be running
var anotherUtil = Create(serviceName);
Expect(anotherUtil.IsInstalled)
.To.Be.False();
Expect(anotherUtil.IsMarkedForDelete)
.To.Be.False();
}
[Test]
public void ShouldNotSuccessfullyUninstallWithDefaultUninstallMethod()
{
// by default, Uninstall _should_ wait for the stop / uninstall
// but _not_ kill (in case of loss of data)
// Arrange
var serviceExe = StubbornServiceExe;
var serviceName = $"stubborn-service{Guid.NewGuid()}";
var util = Create(
serviceName,
serviceName,
serviceExe
);
using var _ = new AutoResetter(Noop, () => util.Uninstall(
ControlOptions.Force | ControlOptions.Wait
));
util.InstallAndStart();
// Act
Expect(() => util.Uninstall())
.To.Throw<ServiceOperationException>()
.With.Message.Containing("Unable to perform Stop");
// Assert
Expect(util.IsInstalled)
.To.Be.True();
Process process = null;
Expect(() => process = Process.GetProcessById(util.ServicePID))
.Not.To.Throw();
Expect(process.HasExited)
.To.Be.False();
}
}
[Test]
[Explicit("Slow and flaky")]
public void ServiceWithArgs()
{
// Arrange
var myPath = new Uri(GetType().Assembly.Location).LocalPath;
var myDir = Path.GetDirectoryName(myPath);
var serviceExe = Path.Combine(myDir, "ServiceWithArgs.exe");
var logFile = Path.Combine(myDir, "service.log");
var arg1 = GetRandomString(3);
var arg2 = GetRandomString(3);
var args = new[] { logFile, arg1, arg2 }.Select(p => p.QuoteIfSpaced());
var serviceName = "test-service-foo-bar";
var displayName = "Test Service - Foo,Bar";
var commandline = string.Join(
" ",
new[] { serviceExe }
.Concat(args)
);
var util = new WindowsServiceUtil(
serviceName,
displayName,
commandline
);
if (util.IsInstalled)
{
util.Uninstall();
}
if (File.Exists(logFile))
{
File.Delete(logFile);
}
// Act
using var resetter = new AutoResetter(
() => util.Install(),
() => util.Uninstall(true));
util.Install();
// Assert
Expect(util.IsInstalled)
.To.Be.True();
util.Start();
Expect(util.State)
.To.Equal(ServiceState.Running);
Expect(logFile)
.To.Exist();
var logData = TryReadAllLinesFrom(logFile);
Expect(logData)
.Not.To.Be.Empty();
Expect(logData[0])
.To.Contain(arg1)
.Then(arg2);
util.Stop();
Expect(util.State)
.To.Equal(ServiceState.Stopped);
var anotherUtil = Create(serviceName);
Expect(anotherUtil.Commandline)
.To.Equal(commandline);
Expect(anotherUtil.ServiceExe)
.To.Equal(serviceExe);
Expect(anotherUtil.DisplayName)
.To.Equal(displayName);
}
private string SpacedServiceExe =>
_spacedServiceExe ??= FindPath(
"SpacedService",
"SpacedService.exe",
p => !p.Contains("obj")
);
private static string StubbornServiceExe =>
_stubbornServiceExe ??= FindPath(
"StubbornService",
"StubbornService.exe",
p => !p.Contains("obj")
);
private static string _stubbornServiceExe;
private string _spacedServiceExe;
private Guid SpacedServiceIdentifier =>
_spacedServiceIdentifier ??= Guid.NewGuid();
private Guid? _spacedServiceIdentifier;
private string SpacedServiceName =>
_spacedServiceName ??= $"SpacedService-{SpacedServiceIdentifier}";
private string SpacedServiceDisplayName => $"Spaced Service {SpacedServiceIdentifier}";
private string _spacedServiceName;
[Test]
[Explicit("Slow and flaky")]
public void InstallingServiceWithSpacedPath()
{
// Arrange
Expect(SpacedServiceExe)
.Not.To.Be.Null();
var sut = Create(
SpacedServiceName,
SpacedServiceDisplayName,
$"\"{SpacedServiceExe}\" --arg --another-arg"
);
sut.ServiceStateExtraWaitSeconds = 30;
// Act
var completed = false;
using var _ = new AutoResetter(Noop, () =>
{
if (completed)
{
return;
}
EnsureServiceNotRunning(
SpacedServiceName,
SpacedServiceExe
);
});
Expect(sut.Install)
.Not.To.Throw();
// Assert
Expect(sut.Start)
.Not.To.Throw();
Expect(sut.State)
.To.Equal(ServiceState.Running);
sut.Stop();
Expect(sut.State)
.To.Equal(ServiceState.Stopped);
sut.Uninstall();
// signal the safety-net that it doesn't have to do anything
completed = true;
}
private static void Noop()
{
}
private void EnsureServiceNotRunning(string name, string exe)
{
// big hammer to enforce service non-existence at exit
// attempt stop
using var stop = new ProcessIO("sc", "stop", name);
stop.StandardOutput.ForEach(Log);
stop.StandardError.ForEach(Log);
// delete service
using var delete = new ProcessIO("sc", "delete", name);
delete.StandardOutput.ForEach(Log);
delete.StandardError.ForEach(Log);
// kill remaining process
var proc = Process.GetProcesses()
.Where(p =>
{
try
{
return p.StartInfo.FileName.Equals(exe, StringComparison.OrdinalIgnoreCase);
}
catch
{
return false;
}
})
.ToArray();
proc.ForEach(p =>
{
try
{
p.Kill();
}
catch
{
// may already be dead
}
});
void Log(string s)
{
Console.WriteLine(s);
}
}
private static WindowsServiceUtil Create(string serviceName)
{
return new WindowsServiceUtil(serviceName);
}
private static IWindowsServiceUtil Create(
string serviceName,
string displayName,
string commandline)
{
return new WindowsServiceUtil(
serviceName,
displayName,
commandline
);
}
private static string FindPath(
string travelUpToFindFolder,
string searchForThisFile,
Func<string, bool> extraMatcher)
{
var current = Path.GetDirectoryName(
new Uri(
typeof(TestWindowsServiceUtil)
.Assembly
.Location
).LocalPath
);
var start = current;
string test;
do
{
current = Path.GetDirectoryName(current);
if (current is null)
{
throw new InvalidOperationException(
$"Can't find {travelUpToFindFolder} traversing up from {start}"
);
}
test = Path.Combine(current, travelUpToFindFolder);
} while (!Directory.Exists(test));
var fs = new LocalFileSystem(test);
var matches = fs.ListRecursive(searchForThisFile)
.Select(p => Path.Combine(test, p))
.ToArray();
return matches.FirstOrDefault(extraMatcher);
}
private string[] TryReadAllLinesFrom(string path)
{
var attempts = 0;
do
{
try
{
return File.ReadAllLines(path);
}
catch
{
Thread.Sleep(100);
}
} while (++attempts < 10);
throw new Exception($"Can't read from file: {path}");
}
private static readonly string TestServiceName = $"test-service-{Guid.NewGuid()}";
private void Do(
string message,
Action toRun,
TimeSpan? maxWait = null)
{
maxWait = maxWait ?? TimeSpan.FromSeconds(5);
var pad = 32 - message.Length - 7;
var padString = "";
if (pad > 0)
{
padString = new String(' ', pad);
}
Console.Out.Write($"{message}{padString}");
Console.Out.Flush();
try
{
TryRun(toRun, maxWait.Value);
Console.Out.WriteLine(" [ OK ]");
}
catch
{
Console.Out.WriteLine(" [FAIL]");
throw;
}
}
private void TryRun(
Action toRun,
TimeSpan maxWaitForSuccess)
{
var giveUp = DateTime.Now + maxWaitForSuccess;
Exception last = null;
while (DateTime.Now <= giveUp)
{
try
{
toRun();
return;
}
catch (Exception ex)
{
last = ex;
}
}
throw last ?? new InvalidOperationException($"No last exception captured");
}
[TearDown]
public void Teardown()
{
EnsureTestServiceIsNotInstalled();
}
[SetUp]
public void Setup()
{
EnsureTestServiceIsNotInstalled();
}
private void Run(
string program,
params string[] args)
{
using var proc = new Process();
var si = proc.StartInfo;
si.FileName = program;
si.Arguments = args.Select(QuoteIfNecessary).JoinWith(" ");
si.RedirectStandardError = true;
si.RedirectStandardInput = true;
si.RedirectStandardOutput = true;
si.CreateNoWindow = true;
si.UseShellExecute = false;
if (!proc.Start())
{
throw new ApplicationException($"Can't start {program} {args.JoinWith(" ")}");
}
proc.WaitForExit();
if (proc.ExitCode != 0)
{
throw new Exception($"{program} {args.JoinWith(" ")}\nexited with code {proc.ExitCode}");
}
}
private static string TestServicePath =>
Path.Combine(
Path.GetDirectoryName(
new Uri(typeof(TestWindowsServiceUtil).Assembly.Location).LocalPath
), "TestService.exe"
);
private string QuoteIfNecessary(string arg)
{
return arg?.Contains(" ") ?? false
? $"\"{arg}\""
: arg;
}
private static void TryDo(Action action)
{
try
{
action();
}
catch
{
/* intentionally left blank */
}
}
private void EnsureTestServiceIsNotInstalled()
{
// attempts to stop and uninstall all found test service instances
var serviceNames = new List<string>();
using (var io = new ProcessIO("sc", "query", "type=", "service", "state=", "all"))
{
serviceNames.AddRange(
io.StandardOutput
.Select(line => line.Trim())
.Where(line => line.StartsWith("SERVICE_NAME"))
.Select(line => string.Join(":", line.Split(':').Skip(1)).Trim())
.Where(serviceName => serviceName.StartsWith("test-service-"))
.ToArray()
);
}
serviceNames.ForEach(serviceName =>
{
TryDo(() => Run("sc", "stop", serviceName));
TryDo(() => Run("sc", "delete", serviceName));
});
}
}
// TODO: this might be useful in PB.Utils; however this very variant is
// super-windows-specific, so one needs to come up with a better cross-platform
// variant; perhaps 'ps' for *nix?
public static class ProcessExtensions
{
public static string QueryCommandline(
this Process proc)
{
if (proc == null || proc.HasExited || proc.Id < 1)
{
return ""; // nothing we can do
}
var query = $"select CommandLine from Win32_Process where ProcessId={proc.Id}";
var searcher = new ManagementObjectSearcher(query);
var collection = searcher.Get();
foreach (var o in collection)
{
return o["CommandLine"]?.ToString() ?? "";
}
return "";
}
}
}