forked from tgstation/tgstation-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcessExecutor.cs
370 lines (329 loc) · 10.6 KB
/
ProcessExecutor.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Tgstation.Server.Host.IO;
namespace Tgstation.Server.Host.System
{
/// <inheritdoc />
sealed class ProcessExecutor : IProcessExecutor
{
/// <summary>
/// <see cref="ReaderWriterLockSlim"/> for <see cref="WithProcessLaunchExclusivity(Action)"/>.
/// </summary>
static readonly ReaderWriterLockSlim ExclusiveProcessLaunchLock = new();
/// <summary>
/// The <see cref="IProcessFeatures"/> for the <see cref="ProcessExecutor"/>.
/// </summary>
readonly IProcessFeatures processFeatures;
/// <summary>
/// The <see cref="IIOManager"/> for the <see cref="ProcessExecutor"/>.
/// </summary>
readonly IIOManager ioManager;
/// <summary>
/// The <see cref="ILogger"/> for the <see cref="ProcessExecutor"/>.
/// </summary>
readonly ILogger<ProcessExecutor> logger;
/// <summary>
/// The <see cref="ILoggerFactory"/> for the <see cref="ProcessExecutor"/>.
/// </summary>
readonly ILoggerFactory loggerFactory;
/// <summary>
/// Runs a given <paramref name="action"/> making sure to not launch any processes while its running.
/// </summary>
/// <param name="action">The <see cref="Action"/> to execute.</param>
public static void WithProcessLaunchExclusivity(Action action)
{
ExclusiveProcessLaunchLock.EnterWriteLock();
try
{
action();
}
finally
{
ExclusiveProcessLaunchLock.ExitWriteLock();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ProcessExecutor"/> class.
/// </summary>
/// <param name="processFeatures">The value of <see cref="processFeatures"/>.</param>
/// <param name="ioManager">The value of <see cref="ioManager"/>.</param>
/// <param name="logger">The value of <see cref="logger"/>.</param>
/// <param name="loggerFactory">The value of <see cref="loggerFactory"/>.</param>
public ProcessExecutor(
IProcessFeatures processFeatures,
IIOManager ioManager,
ILogger<ProcessExecutor> logger,
ILoggerFactory loggerFactory)
{
this.processFeatures = processFeatures ?? throw new ArgumentNullException(nameof(processFeatures));
this.ioManager = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
}
/// <inheritdoc />
public IProcess? GetProcess(int id)
{
logger.LogDebug("Attaching to process {pid}...", id);
global::System.Diagnostics.Process handle;
try
{
handle = global::System.Diagnostics.Process.GetProcessById(id);
}
catch (Exception e)
{
logger.LogDebug(e, "Unable to get process {pid}!", id);
return null;
}
return CreateFromExistingHandle(handle);
}
/// <inheritdoc />
public IProcess GetCurrentProcess()
{
logger.LogTrace("Getting current process...");
var handle = global::System.Diagnostics.Process.GetCurrentProcess();
return CreateFromExistingHandle(handle);
}
/// <inheritdoc />
public async ValueTask<IProcess> LaunchProcess(
string fileName,
string workingDirectory,
string arguments,
CancellationToken cancellationToken,
IReadOnlyDictionary<string, string>? environment,
string? fileRedirect,
bool readStandardHandles,
bool noShellExecute)
{
ArgumentNullException.ThrowIfNull(fileName);
ArgumentNullException.ThrowIfNull(workingDirectory);
ArgumentNullException.ThrowIfNull(arguments);
var enviromentLogLines = environment == null
? String.Empty
: String.Concat(environment.Select(kvp => $"{Environment.NewLine}\t- {kvp.Key}={kvp.Value}"));
if (noShellExecute)
logger.LogDebug(
"Launching process in {workingDirectory}: {exe} {arguments}{environment}",
workingDirectory,
fileName,
arguments,
enviromentLogLines);
else
logger.LogDebug(
"Shell launching process in {workingDirectory}: {exe} {arguments}{environment}",
workingDirectory,
fileName,
arguments,
enviromentLogLines);
var handle = new global::System.Diagnostics.Process();
try
{
handle.StartInfo.FileName = fileName;
handle.StartInfo.Arguments = arguments;
if (environment != null)
foreach (var kvp in environment)
handle.StartInfo.Environment.Add(kvp!);
handle.StartInfo.WorkingDirectory = workingDirectory;
handle.StartInfo.UseShellExecute = !noShellExecute;
Task<string?>? readTask = null;
CancellationTokenSource? disposeCts = null;
try
{
TaskCompletionSource<int>? processStartTcs = null;
if (readStandardHandles)
{
processStartTcs = new TaskCompletionSource<int>();
disposeCts = new CancellationTokenSource();
readTask = ConsumeReaders(handle, processStartTcs.Task, fileRedirect, disposeCts.Token);
}
int pid;
try
{
ExclusiveProcessLaunchLock.EnterReadLock();
try
{
handle.Start();
}
finally
{
ExclusiveProcessLaunchLock.ExitReadLock();
}
try
{
pid = await processFeatures.HandleProcessStart(handle, cancellationToken);
}
catch
{
handle.Kill();
throw;
}
processStartTcs?.SetResult(pid);
}
catch (Exception ex)
{
processStartTcs?.SetException(ex);
throw;
}
var process = new Process(
processFeatures,
handle,
disposeCts,
readTask,
loggerFactory.CreateLogger<Process>(),
false);
return process;
}
catch
{
disposeCts?.Dispose();
throw;
}
}
catch
{
handle.Dispose();
throw;
}
}
/// <inheritdoc />
public IProcess? GetProcessByName(string name)
{
logger.LogTrace("GetProcessByName: {processName}...", name ?? throw new ArgumentNullException(nameof(name)));
var procs = global::System.Diagnostics.Process.GetProcessesByName(name);
global::System.Diagnostics.Process? handle = null;
foreach (var proc in procs)
if (handle == null)
handle = proc;
else
{
logger.LogTrace("Disposing extra found PID: {pid}...", proc.Id);
proc.Dispose();
}
if (handle == null)
return null;
return CreateFromExistingHandle(handle);
}
/// <summary>
/// Consume the stdout/stderr streams into a <see cref="Task"/>.
/// </summary>
/// <param name="handle">The <see cref="global::System.Diagnostics.Process"/>.</param>
/// <param name="startupAndPid">The <see cref="Task{TResult}"/> resulting in the <see cref="global::System.Diagnostics.Process.Id"/> of the started process.</param>
/// <param name="fileRedirect">The optional path to redirect the streams to.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation.</param>
/// <returns>A <see cref="Task{TResult}"/> resulting in the program's output/error text if <paramref name="fileRedirect"/> is <see langword="null"/>, <see langword="null"/> otherwise.</returns>
async Task<string?> ConsumeReaders(global::System.Diagnostics.Process handle, Task<int> startupAndPid, string? fileRedirect, CancellationToken cancellationToken)
{
handle.StartInfo.RedirectStandardOutput = true;
handle.StartInfo.RedirectStandardError = true;
bool writingToFile;
await using var fileStream = (writingToFile = fileRedirect != null) ? ioManager.CreateAsyncSequentialWriteStream(fileRedirect!) : null;
await using var fileWriter = fileStream != null ? new StreamWriter(fileStream) : null;
var stringBuilder = fileStream == null ? new StringBuilder() : null;
var dataChannel = Channel.CreateUnbounded<string>(
new UnboundedChannelOptions
{
AllowSynchronousContinuations = !writingToFile,
SingleReader = true,
SingleWriter = false,
});
var handlesOpen = 2;
async void DataReceivedHandler(object sender, DataReceivedEventArgs eventArgs)
{
var line = eventArgs.Data;
if (line == null)
{
var handlesRemaining = Interlocked.Decrement(ref handlesOpen);
if (handlesRemaining == 0)
dataChannel.Writer.Complete();
return;
}
try
{
await dataChannel.Writer.WriteAsync(line, cancellationToken);
}
catch (OperationCanceledException ex)
{
logger.LogWarning(ex, "Handle channel write interrupted!");
}
}
handle.OutputDataReceived += DataReceivedHandler;
handle.ErrorDataReceived += DataReceivedHandler;
async ValueTask OutputWriter()
{
var enumerable = dataChannel.Reader.ReadAllAsync(cancellationToken);
if (writingToFile)
{
var enumerator = enumerable.GetAsyncEnumerator(cancellationToken);
var nextEnumeration = enumerator.MoveNextAsync();
while (await nextEnumeration)
{
var text = enumerator.Current;
nextEnumeration = enumerator.MoveNextAsync();
await fileWriter!.WriteLineAsync(text.AsMemory(), cancellationToken);
if (!nextEnumeration.IsCompleted)
await fileWriter.FlushAsync(cancellationToken);
}
}
else
await foreach (var text in enumerable)
stringBuilder!.AppendLine(text);
}
var pid = await startupAndPid;
logger.LogTrace("Starting read for PID {pid}...", pid);
using (cancellationToken.Register(() => dataChannel.Writer.TryComplete()))
{
handle.BeginOutputReadLine();
using (cancellationToken.Register(handle.CancelOutputRead))
{
handle.BeginErrorReadLine();
using (cancellationToken.Register(handle.CancelErrorRead))
{
try
{
await OutputWriter();
logger.LogTrace("Finished read for PID {pid}", pid);
}
catch (OperationCanceledException ex)
{
logger.LogWarning(ex, "PID {pid} stream reading interrupted!", pid);
if (writingToFile)
await fileWriter!.WriteLineAsync("-- Process detached, log truncated. This is likely due a to TGS restart --");
}
}
}
}
return stringBuilder?.ToString();
}
/// <summary>
/// Create a <see cref="IProcess"/> given an existing <paramref name="handle"/>.
/// </summary>
/// <param name="handle">The <see cref="global::System.Diagnostics.Process"/> to create a <see cref="IProcess"/> from.</param>
/// <returns>The <see cref="IProcess"/> based on <paramref name="handle"/>.</returns>
Process CreateFromExistingHandle(global::System.Diagnostics.Process handle)
{
try
{
var pid = handle.Id;
return new Process(
processFeatures,
handle,
null,
null,
loggerFactory.CreateLogger<Process>(),
true);
}
catch
{
handle.Dispose();
throw;
}
}
}
}