-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ShutdownCommand.cs
93 lines (78 loc) · 3.1 KB
/
ShutdownCommand.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using Microsoft.NET.Sdk.Razor.Tool.CommandLineUtils;
namespace Microsoft.NET.Sdk.Razor.Tool
{
internal class ShutdownCommand : CommandBase
{
public ShutdownCommand(Application parent)
: base(parent, "shutdown")
{
Pipe = Option("-p|--pipe", "name of named pipe", CommandOptionType.SingleValue);
Wait = Option("-w|--wait", "wait for shutdown", CommandOptionType.NoValue);
}
public CommandOption Pipe { get; }
public CommandOption Wait { get; }
protected override bool ValidateArguments()
{
if (string.IsNullOrEmpty(Pipe.Value()))
{
Pipe.Values.Add(PipeName.ComputeDefault());
}
return true;
}
protected async override Task<int> ExecuteCoreAsync()
{
if (!IsServerRunning())
{
// server isn't running right now
Out.Write("Server is not running.");
return 0;
}
try
{
using (var client = await Client.ConnectAsync(Pipe.Value(), timeout: TimeSpan.FromSeconds(5), cancellationToken: Cancelled))
{
if (client == null)
{
throw new InvalidOperationException("Couldn't connect to the server.");
}
var request = ServerRequest.CreateShutdown();
await request.WriteAsync(client.Stream, Cancelled).ConfigureAwait(false);
var response = ((ShutdownServerResponse)await ServerResponse.ReadAsync(client.Stream, Cancelled));
if (Wait.HasValue())
{
try
{
var process = Process.GetProcessById(response.ServerProcessId);
process.WaitForExit();
}
catch (Exception ex)
{
// There is an inherent race here with the server process. If it has already shutdown
// by the time we try to access it then the operation has succeeded.
Error.Write(ex);
}
Out.Write("Server pid:{0} shut down completed.", response.ServerProcessId);
}
}
}
catch (Exception ex) when (IsServerRunning())
{
// Ignore an exception that occurred while the server was shutting down.
Error.Write(ex);
}
return 0;
}
private bool IsServerRunning()
{
if (Mutex.TryOpenExisting(MutexName.GetServerMutexName(Pipe.Value()), out var mutex))
{
mutex.Dispose();
return true;
}
return false;
}
}
}