This repository has been archived by the owner on Jan 18, 2022. It is now read-only.
/
SpatialDeploymentManager.cs
263 lines (220 loc) · 7.91 KB
/
SpatialDeploymentManager.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Improbable.Gdk.Tools;
using Debug = UnityEngine.Debug;
namespace Improbable.Gdk.TestUtils.Editor
{
/// <summary>
/// Manages a single `spatial local launch` instance.
/// </summary>
public class SpatialDeploymentManager : IDisposable
{
private Process spatialProcess;
public static async Task<SpatialDeploymentManager> Start(string deploymentJsonPath, string snapshotPath)
{
if (!File.Exists(Path.Combine(Common.SpatialProjectRootDir, deploymentJsonPath)))
{
throw new ArgumentException($"Could not find deployment config at {deploymentJsonPath}");
}
if (!File.Exists(Path.Combine(Common.SpatialProjectRootDir, snapshotPath)))
{
throw new ArgumentException($"Could not find snapshot at {snapshotPath}");
}
await BuildWorkerConfigs().ConfigureAwait(false);
var process = await StartSpatial(deploymentJsonPath, snapshotPath).ConfigureAwait(false);
return new SpatialDeploymentManager
{
spatialProcess = process
};
}
private static Task BuildWorkerConfigs()
{
var tcs = new TaskCompletionSource<bool>();
var processInfo =
new ProcessStartInfo(Common.SpatialBinary, "build build-config")
{
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
WorkingDirectory = Common.SpatialProjectRootDir
};
var process = new Process
{
StartInfo = processInfo,
EnableRaisingEvents = true
};
process.Exited += (sender, args) =>
{
if (process.ExitCode == 0)
{
tcs.SetResult(true);
}
else
{
tcs.TrySetException(
new Exception($@"Failed to build worker configs with exit code: {process.ExitCode}.
Raw output:
{process.StandardOutput.ReadToEnd()}
Raw stderr:
{process.StandardError.ReadToEnd()}"));
}
process.Dispose();
};
process.Start();
return tcs.Task;
}
private static Task<Process> StartSpatial(string deploymentJsonPath, string snapshotPath)
{
var tcs = new TaskCompletionSource<Process>();
var processInfo =
new ProcessStartInfo(Common.SpatialBinary, $"local launch \"{deploymentJsonPath}\" --snapshot \"{snapshotPath}\" --enable_pre_run_check=false")
{
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
WorkingDirectory = Common.SpatialProjectRootDir
};
var process = new Process
{
StartInfo = processInfo,
EnableRaisingEvents = true
};
var output = new StringBuilder();
process.Exited += (sender, args) =>
{
tcs.TrySetException(
new Exception($"Spatial process failed to start. Raw output:\n{output.ToString()}"));
};
process.OutputDataReceived += (sender, args) =>
{
if (string.IsNullOrEmpty(args.Data))
{
return;
}
if (args.Data.Contains("localhost:21000/inspector-v2"))
{
tcs.TrySetResult(process);
}
output.AppendLine(args.Data);
};
process.Start();
process.BeginOutputReadLine();
return tcs.Task;
}
public void Dispose()
{
var success = spatialProcess.KillTree();
if (success != 0)
{
Debug.LogWarning("Failed to stop spatial process tree.");
}
}
}
// Copied from: https://raw.githubusercontent.com/dotnet/cli/master/test/Microsoft.DotNet.Tools.Tests.Utilities/Extensions/ProcessExtensions.cs
// Licensed under MIT.
public static class ProcessExtensions
{
private static readonly bool IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(value: 30);
public static int KillTree(this Process process)
{
return process.KillTree(DefaultTimeout);
}
public static int KillTree(this Process process, TimeSpan timeout)
{
if (IsWindows)
{
return RunProcessAndWaitForExit(
"taskkill",
$"/T /F /PID {process.Id}",
timeout,
out _,
out _);
}
var children = new HashSet<int>();
if (GetAllChildIdsUnix(process.Id, children, timeout) != 0)
{
return 1;
}
foreach (var childId in children)
{
if (KillProcessUnix(childId, timeout) != 0)
{
return 1;
}
}
return KillProcessUnix(process.Id, timeout);
}
private static int GetAllChildIdsUnix(int parentId, ISet<int> children, TimeSpan timeout)
{
var exitCode = RunProcessAndWaitForExit(
"pgrep",
$"-P {parentId}",
timeout,
out var stdout,
out _);
if (exitCode == 0 && !string.IsNullOrEmpty(stdout))
{
using (var reader = new StringReader(stdout))
{
while (true)
{
var text = reader.ReadLine();
if (string.IsNullOrEmpty(text))
{
break;
}
if (int.TryParse(text, out var id))
{
children.Add(id);
// Recursively get the children
GetAllChildIdsUnix(id, children, timeout);
}
}
}
}
return exitCode;
}
private static int KillProcessUnix(int processId, TimeSpan timeout)
{
return RunProcessAndWaitForExit(
"kill",
$"-KILL {processId}",
timeout,
out _,
out _);
}
private static int RunProcessAndWaitForExit(string fileName, string arguments, TimeSpan timeout,
out string stdout, out string stderr)
{
var startInfo = new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
var process = Process.Start(startInfo);
stdout = null;
stderr = null;
if (process.WaitForExit((int) timeout.TotalMilliseconds))
{
stdout = process.StandardOutput.ReadToEnd();
stderr = process.StandardError.ReadToEnd();
}
else
{
process.Kill();
}
return process.ExitCode;
}
}
}