-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathProcessEx.cs
260 lines (218 loc) · 7.96 KB
/
ProcessEx.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Internal;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Internal;
internal sealed class ProcessEx : IDisposable
{
private static readonly TimeSpan DefaultProcessTimeout = TimeSpan.FromMinutes(15);
private static readonly string NUGET_PACKAGES = GetNugetPackagesRestorePath();
private readonly ITestOutputHelper _output;
private readonly Process _process;
private readonly StringBuilder _stderrCapture;
private readonly StringBuilder _stdoutCapture;
private readonly object _pipeCaptureLock = new object();
private readonly object _testOutputLock = new object();
private BlockingCollection<string> _stdoutLines;
private readonly TaskCompletionSource<int> _exited;
private readonly CancellationTokenSource _stdoutLinesCancellationSource = new CancellationTokenSource(TimeSpan.FromMinutes(5));
private readonly CancellationTokenSource _processTimeoutCts;
private bool _disposed;
public ProcessEx(ITestOutputHelper output, Process proc, TimeSpan timeout)
{
_output = output;
_stdoutCapture = new StringBuilder();
_stderrCapture = new StringBuilder();
_stdoutLines = new BlockingCollection<string>();
_exited = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
_process = proc;
proc.EnableRaisingEvents = true;
proc.OutputDataReceived += OnOutputData;
proc.ErrorDataReceived += OnErrorData;
proc.Exited += OnProcessExited;
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
if (proc.HasExited)
{
OnProcessExited();
}
// We greedily create a timeout exception message even though a timeout is unlikely to happen for two reasons:
// 1. To make it less likely for Process getters to throw exceptions like "System.InvalidOperationException: Process has exited, ..."
// 2. To ensure if/when exceptions are thrown from Process getters, these exceptions can easily be observed.
var timeoutExMessage = $"Process proc {proc.ProcessName} {proc.StartInfo.Arguments} timed out after {timeout}.";
_processTimeoutCts = new CancellationTokenSource(timeout);
_processTimeoutCts.Token.Register(() =>
{
_exited.TrySetException(new TimeoutException(timeoutExMessage));
});
}
public Process Process => _process;
public Task Exited => _exited.Task;
public bool HasExited => _process.HasExited;
public string Error
{
get
{
lock (_pipeCaptureLock)
{
return _stderrCapture.ToString();
}
}
}
public string Output
{
get
{
lock (_pipeCaptureLock)
{
return _stdoutCapture.ToString();
}
}
}
public IEnumerable<string> OutputLinesAsEnumerable => _stdoutLines.GetConsumingEnumerable(_stdoutLinesCancellationSource.Token);
public int ExitCode => _process.ExitCode;
public object Id => _process.Id;
public static ProcessEx Run(ITestOutputHelper output, string workingDirectory, string command, string args = null, IDictionary<string, string> envVars = null, TimeSpan? timeout = default)
{
var startInfo = new ProcessStartInfo(command, args)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = workingDirectory
};
if (envVars != null)
{
foreach (var envVar in envVars)
{
startInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
}
}
startInfo.EnvironmentVariables["NUGET_PACKAGES"] = NUGET_PACKAGES;
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("helix")))
{
startInfo.EnvironmentVariables["NUGET_FALLBACK_PACKAGES"] = Environment.GetEnvironmentVariable("NUGET_FALLBACK_PACKAGES");
}
output.WriteLine($"==> {startInfo.FileName} {startInfo.Arguments} [{startInfo.WorkingDirectory}]");
var proc = Process.Start(startInfo);
return new ProcessEx(output, proc, timeout ?? DefaultProcessTimeout);
}
private void OnErrorData(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
{
return;
}
lock (_pipeCaptureLock)
{
_stderrCapture.AppendLine(e.Data);
}
lock (_testOutputLock)
{
if (!_disposed)
{
_output.WriteLine("[ERROR] " + e.Data);
}
}
}
private void OnOutputData(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
{
return;
}
lock (_pipeCaptureLock)
{
_stdoutCapture.AppendLine(e.Data);
}
lock (_testOutputLock)
{
if (!_disposed)
{
_output.WriteLine(e.Data);
}
}
_stdoutLines?.Add(e.Data);
}
private void OnProcessExited(object sender = null, EventArgs e = null)
{
lock (_testOutputLock)
{
if (!_disposed)
{
_output.WriteLine("Process exited.");
}
}
// Don't remove this line - There is a race condition where the process exits and we grab the output before the stdout/stderr completed writing.
_process.WaitForExit();
_stdoutLines?.CompleteAdding();
_stdoutLines = null;
_exited.TrySetResult(_process.ExitCode);
}
internal string GetFormattedOutput()
{
if (!_process.HasExited)
{
Assert.Fail($"Process {_process.ProcessName} with pid: {_process.Id} has not finished running.");
}
return $"Process exited with code {_process.ExitCode}\nStdErr: {Error}\nStdOut: {Output}";
}
public void WaitForExit(bool assertSuccess, TimeSpan? timeSpan = null)
{
if (!timeSpan.HasValue)
{
timeSpan = TimeSpan.FromSeconds(600);
}
var exited = Exited.Wait(timeSpan.Value);
if (!exited)
{
lock (_testOutputLock)
{
_output.WriteLine($"The process didn't exit within the allotted time ({timeSpan.Value.TotalSeconds} seconds).");
}
_process.Dispose();
}
else if (assertSuccess && _process.ExitCode != 0)
{
Assert.Fail($"Process exited with code {_process.ExitCode}\nStdErr: {Error}\nStdOut: {Output}");
}
}
private static string GetNugetPackagesRestorePath() => (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("NUGET_RESTORE")))
? typeof(ProcessEx).Assembly
.GetCustomAttributes<AssemblyMetadataAttribute>()
.FirstOrDefault(attribute => attribute.Key == "TestPackageRestorePath")
?.Value
: Environment.GetEnvironmentVariable("NUGET_RESTORE");
public void Dispose()
{
_processTimeoutCts.Dispose();
lock (_testOutputLock)
{
_disposed = true;
}
if (_process != null && !_process.HasExited)
{
_process.KillTree();
}
if (_process != null)
{
_process.CancelOutputRead();
_process.CancelErrorRead();
_process.ErrorDataReceived -= OnErrorData;
_process.OutputDataReceived -= OnOutputData;
_process.Exited -= OnProcessExited;
_process.Dispose();
}
}
}