-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessRunner.cs
More file actions
78 lines (70 loc) · 3.02 KB
/
Copy pathProcessRunner.cs
File metadata and controls
78 lines (70 loc) · 3.02 KB
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
using System.Diagnostics;
using System.Text;
namespace DbBackupTool
{
// Shared "shell out to a native CLI tool and check the result" helper - every
// provider (exp, sqlcmd, mysqldump) goes through this exact same path, which is
// what keeps the three providers this uniform. Uses ArgumentList (not a
// hand-built command string) so arguments containing spaces/quotes - file paths,
// passwords - can never break quoting.
public static class ProcessRunner
{
public static async Task<string> RunAsync(
string fileName, IEnumerable<string> args, TimeSpan timeout, CancellationToken ct,
IDictionary<string, string>? environmentVariables = null)
{
var psi = new ProcessStartInfo
{
FileName = fileName,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
foreach (var a in args) psi.ArgumentList.Add(a);
if (environmentVariables != null)
foreach (var (key, value) in environmentVariables)
psi.Environment[key] = value;
using var process = new Process { StartInfo = psi };
var stdout = new StringBuilder();
var stderr = new StringBuilder();
process.OutputDataReceived += (_, e) => { if (e.Data != null) stdout.AppendLine(e.Data); };
process.ErrorDataReceived += (_, e) => { if (e.Data != null) stderr.AppendLine(e.Data); };
try
{
process.Start();
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Could not start '{fileName}'. Is it installed and on PATH (or is the configured *Path setting a full path)? {ex.Message}", ex);
}
process.BeginOutputReadLine();
process.BeginErrorReadLine();
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeoutCts.CancelAfter(timeout);
try
{
await process.WaitForExitAsync(timeoutCts.Token);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
TryKill(process);
throw new TimeoutException($"{fileName} timed out after {timeout}.\nSTDOUT:\n{stdout}\nSTDERR:\n{stderr}");
}
catch (OperationCanceledException)
{
TryKill(process);
throw;
}
if (process.ExitCode != 0)
throw new InvalidOperationException(
$"{fileName} exited with code {process.ExitCode}.\nSTDOUT:\n{stdout}\nSTDERR:\n{stderr}");
return stdout.ToString().Trim();
}
private static void TryKill(Process process)
{
try { process.Kill(entireProcessTree: true); } catch { /* best effort */ }
}
}
}