-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathProcess.cs
241 lines (207 loc) · 6.45 KB
/
Process.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
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Win32.SafeHandles;
using Tgstation.Server.Host.IO;
namespace Tgstation.Server.Host.System
{
/// <inheritdoc />
sealed class Process : IProcess
{
/// <inheritdoc />
public int Id { get; }
/// <inheritdoc />
public Task Startup { get; }
/// <inheritdoc />
public Task<int?> Lifetime { get; }
/// <summary>
/// The <see cref="IProcessFeatures"/> for the <see cref="Process"/>.
/// </summary>
readonly IProcessFeatures processFeatures;
/// <summary>
/// The <see cref="ILogger"/> for the <see cref="Process"/>.
/// </summary>
readonly ILogger<Process> logger;
/// <summary>
/// The <see cref="global::System.Diagnostics.Process"/> <see cref="object"/>.
/// </summary>
readonly global::System.Diagnostics.Process handle;
/// <summary>
/// The <see cref="CancellationTokenSource"/> used to shutdown the <see cref="readTask"/> and <see cref="Lifetime"/>.
/// </summary>
readonly CancellationTokenSource cancellationTokenSource;
/// <summary>
/// The <see cref="global::System.Diagnostics.Process.SafeHandle"/>.
/// </summary>
/// <remarks>We keep this to prevent .NET from closing the real handle too soon. See https://stackoverflow.com/a/47656845</remarks>
readonly SafeProcessHandle safeHandle;
/// <summary>
/// The <see cref="Task{TResult}"/> resulting in the process' standard output/error text.
/// </summary>
readonly Task<string> readTask;
/// <summary>
/// Initializes a new instance of the <see cref="Process"/> class.
/// </summary>
/// <param name="processFeatures">The value of <see cref="processFeatures"/>.</param>
/// <param name="handle">The value of <see cref="handle"/>.</param>
/// <param name="readerCts">The override value of <see cref="cancellationTokenSource"/>.</param>
/// <param name="readTask">The value of <see cref="readTask"/>.</param>
/// <param name="logger">The value of <see cref="logger"/>.</param>
/// <param name="preExisting">If <paramref name="handle"/> was NOT just created.</param>
public Process(
IProcessFeatures processFeatures,
global::System.Diagnostics.Process handle,
CancellationTokenSource readerCts,
Task<string> readTask,
ILogger<Process> logger,
bool preExisting)
{
this.handle = handle ?? throw new ArgumentNullException(nameof(handle));
// Do this fast because the runtime will bitch if we try to access it after it ends
safeHandle = handle.SafeHandle;
Id = handle.Id;
cancellationTokenSource = readerCts ?? new CancellationTokenSource();
this.processFeatures = processFeatures ?? throw new ArgumentNullException(nameof(processFeatures));
this.readTask = readTask;
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
Lifetime = WrapLifetimeTask();
if (preExisting)
{
Startup = Task.CompletedTask;
return;
}
Startup = Task.Factory.StartNew(
() =>
{
try
{
handle.WaitForInputIdle();
}
catch (Exception ex)
{
logger.LogTrace(ex, "WaitForInputIdle() failed, this is normal.");
}
},
CancellationToken.None, // DCT: None available
DefaultIOManager.BlockingTaskCreationOptions,
TaskScheduler.Current);
logger.LogTrace("Created process ID: {pid}", Id);
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
logger.LogTrace("Disposing PID {pid}...", Id);
cancellationTokenSource.Cancel();
cancellationTokenSource.Dispose();
if (readTask != null)
await readTask;
await Lifetime;
safeHandle.Dispose();
handle.Dispose();
}
/// <inheritdoc />
public Task<string> GetCombinedOutput(CancellationToken cancellationToken)
{
if (readTask == null)
throw new InvalidOperationException("Output/Error stream reading was not enabled!");
return readTask;
}
/// <inheritdoc />
public void Terminate()
{
if (handle.HasExited)
{
logger.LogTrace("PID {pid} already exited", Id);
return;
}
try
{
logger.LogTrace("Terminating PID {pid}...", Id);
handle.Kill();
if (!handle.WaitForExit(5000))
logger.LogWarning("WaitForExit() on PID {pid} timed out!", Id);
}
catch (Exception e)
{
logger.LogDebug(e, "PID {pid} termination exception!", Id);
}
}
/// <inheritdoc />
public void AdjustPriority(bool higher)
{
var targetPriority = higher ? ProcessPriorityClass.AboveNormal : ProcessPriorityClass.BelowNormal;
try
{
handle.PriorityClass = targetPriority;
logger.LogTrace("Set PID {pid} to {targetPriority} priority", Id, targetPriority);
}
catch (Exception ex)
{
logger.LogWarning(ex, "Unable to set priority for PID {id} to {targetPriority}!", Id, targetPriority);
}
}
/// <inheritdoc />
public void Suspend()
{
try
{
processFeatures.SuspendProcess(handle);
logger.LogTrace("Suspended PID {pid}", Id);
}
catch (Exception e)
{
logger.LogError(e, "Failed to suspend PID {pid}!", Id);
throw;
}
}
/// <inheritdoc />
public void Resume()
{
try
{
processFeatures.ResumeProcess(handle);
logger.LogTrace("Resumed PID {pid}", Id);
}
catch (Exception e)
{
logger.LogError(e, "Failed to resume PID {pid}!", Id);
throw;
}
}
/// <inheritdoc />
public string GetExecutingUsername()
{
var result = processFeatures.GetExecutingUsername(handle);
logger.LogTrace("PID {pid} Username: {username}", Id, result);
return result;
}
/// <inheritdoc />
public ValueTask CreateDump(string outputFile, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(outputFile);
logger.LogTrace("Dumping PID {pid} to {dumpFilePath}...", Id, outputFile);
return processFeatures.CreateDump(handle, outputFile, cancellationToken);
}
/// <summary>
/// Attaches a log message to the process' exit event.
/// </summary>
/// <returns>A <see cref="Task{TResult}"/> resulting in the <see cref="global::System.Diagnostics.Process.ExitCode"/> or <see langword="null"/> if the process was detached.</returns>
async Task<int?> WrapLifetimeTask()
{
try
{
await handle.WaitForExitAsync(cancellationTokenSource.Token);
var exitCode = handle.ExitCode;
logger.LogTrace("PID {pid} exited with code {exitCode}", Id, exitCode);
return exitCode;
}
catch (OperationCanceledException ex)
{
logger.LogTrace(ex, "Process lifetime task cancelled!");
return null;
}
}
}
}