This repository has been archived by the owner on Jan 18, 2022. It is now read-only.
/
SpatialdManager.cs
324 lines (272 loc) · 12.3 KB
/
SpatialdManager.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Improbable.Gdk.Tools;
using Improbable.Gdk.Tools.MiniJSON;
using UnityEngine;
namespace Improbable.Gdk.TestUtils.Editor
{
/// <summary>
/// Manages the lifecycle of SpatialD and provides methods to interact with it.
/// </summary>
public class SpatialdManager : IDisposable
{
private static readonly string SpotBinary;
private static readonly string ProjectName;
private static readonly string SpotShimPath;
static SpatialdManager()
{
var spotPath = Path.Combine(Common.GetPackagePath("io.improbable.worker.sdk"), ".spot/spot");
if (Application.platform == RuntimePlatform.WindowsEditor)
{
spotPath = Path.ChangeExtension(spotPath, ".exe");
}
SpotBinary = spotPath;
var spatialJsonFile = Path.Combine(Common.SpatialProjectRootDir, "spatialos.json");
if (!File.Exists(spatialJsonFile))
{
throw new FileNotFoundException($"Could not find a spatialos.json file located at: {spatialJsonFile}");
}
var data = Json.Deserialize(File.ReadAllText(spatialJsonFile));
if (data == null)
{
throw new FormatException($"Could not parse spatialos.json file located at: {spatialJsonFile}");
}
try
{
ProjectName = (string) data["name"];
}
catch (KeyNotFoundException e)
{
throw new FormatException($"Could not find a \"name\" field in {spatialJsonFile}.\n Raw exception: {e.Message}");
}
var packagePath = Common.GetPackagePath("io.improbable.gdk.testutils");
SpotShimPath = Path.Combine(packagePath, ".SpotShim", "SpotShim", "SpotShim");
}
/// <summary>
/// Starts SpatialD.
/// </summary>
/// <remarks>
/// If SpatialD is already running, it will stop that instance and start a new one.
/// </remarks>
/// <exception cref="Exception">Thrown if this fails to start SpatialD.</exception>
public static async Task<SpatialdManager> Start()
{
await RedirectedProcess
.Spatial("service", "stop")
.InDirectory(Common.SpatialProjectRootDir)
.RedirectOutputOptions(OutputRedirectBehaviour.None)
.RunAsync()
.ConfigureAwait(false);
var result = await RedirectedProcess
.Spatial("service", "start")
.InDirectory(Common.SpatialProjectRootDir)
.RedirectOutputOptions(OutputRedirectBehaviour.None)
.RunAsync()
.ConfigureAwait(false);
if (result.ExitCode != 0)
{
throw new Exception($"Could not start spatiald with error:\n {string.Join("\n", result.Stderr)}");
}
return new SpatialdManager();
}
// Hide default constructor.
private SpatialdManager()
{
}
/// <summary>
/// Starts a local deployment asynchronously.
/// </summary>
/// <param name="name">The name for the local deployment.</param>
/// <param name="deploymentJsonPath">
/// The path to the launch configuration JSON relative to the root of the SpatialOS project.
/// </param>
/// <param name="snapshotFileName">
/// The name of the snapshot to use for this deployment. Must be in the snapshots directory of your
/// SpatialOS project.
/// </param>
/// <returns>A task which represents the deployment that was started.</returns>
/// <exception cref="ArgumentException">Thrown if <see cref="deploymentJsonPath"/> does not exist.</exception>
/// <exception cref="Exception">Thrown if the deployment fails to start.</exception>
public async Task<LocalDeployment> StartLocalDeployment(string name, string deploymentJsonPath, string snapshotFileName = "default.snapshot")
{
var fullJsonPath = Path.Combine(Common.SpatialProjectRootDir, deploymentJsonPath);
if (!File.Exists(fullJsonPath))
{
throw new ArgumentException($"Could not find launch config file at {fullJsonPath}");
}
var fullSnapshotPath = Path.Combine(Common.SpatialProjectRootDir, "snapshots", snapshotFileName);
if (!File.Exists(fullSnapshotPath))
{
throw new ArgumentException($"Could not find launch config file at {fullSnapshotPath}");
}
var buildConfigResult = await RedirectedProcess
.Spatial("build", "build-config")
.InDirectory(Common.SpatialProjectRootDir)
.RedirectOutputOptions(OutputRedirectBehaviour.None)
.RunAsync()
.ConfigureAwait(false);
if (buildConfigResult.ExitCode != 0)
{
throw new Exception($"Failed to build worker configs with error:\n {string.Join("\n", buildConfigResult.Stderr)}");
}
var snapshotFile = Path.GetFileNameWithoutExtension(snapshotFileName);
var result = await RedirectedProcess.Command(SpotBinary)
.WithArgs("alpha", "deployment", "create", "-p", ProjectName, "-n", name, "-c", $"\"{fullJsonPath}\"", "-s", snapshotFile, "--json")
.InDirectory(Common.SpatialProjectRootDir)
.RedirectOutputOptions(OutputRedirectBehaviour.None)
.RunAsync()
.ConfigureAwait(false);
if (result.ExitCode != 0)
{
throw new Exception($"Failed to start deployment with error:\n {string.Join("\n", result.Stderr)}");
}
var deploymentData = Json.Deserialize(string.Join("", result.Stdout));
if (deploymentData == null)
{
throw new Exception($"Failed to create deployment because there was no output. Error: \n {string.Join("\n", result.Stderr)}");
}
var content = (Dictionary<string, object>) deploymentData["content"];
var id = (string) content["id"];
return new LocalDeployment(this, id, name, ProjectName);
}
/// <summary>
/// Stops a local deployment asynchronously.
/// </summary>
/// <param name="deployment">The deployment to stop.</param>
/// <returns>A task which represents the operation to stop the deployment.</returns>
/// <exception cref="Exception">Thrown if the deployment fails to be stopped.</exception>
public async Task StopLocalDeployment(LocalDeployment deployment)
{
var result = await RedirectedProcess.Command(SpotBinary)
.WithArgs("alpha", "deployment", "delete", "-i", deployment.Id)
.InDirectory(Common.SpatialProjectRootDir)
.RedirectOutputOptions(OutputRedirectBehaviour.None)
.RunAsync()
.ConfigureAwait(false);
if (result.ExitCode != 0)
{
throw new Exception($"Failed to stop deployment with error:\n {string.Join("\n", result.Stderr)}");
}
}
/// <summary>
/// Gets the details of currently running deployments asynchronously.
/// </summary>
/// <returns>A task which represents list of</returns>
public async Task<List<LocalDeployment>> GetRunningDeployments()
{
var result = await RedirectedProcess.Command(SpotBinary)
.WithArgs("alpha", "deployment", "list", "-p", ProjectName, "-f", "NOT_STOPPED_DEPLOYMENTS", "--json")
.InDirectory(Common.SpatialProjectRootDir)
.RedirectOutputOptions(OutputRedirectBehaviour.None)
.RunAsync()
.ConfigureAwait(false);
if (result.ExitCode != 0)
{
throw new Exception($"Failed to list deployments with error:\n {string.Join("\n", result.Stderr)}");
}
var json = Json.Deserialize(string.Join("", result.Stdout));
if (json == null)
{
throw new Exception($"Failed to list deployments because there was no output. Error: \n {string.Join("\n", result.Stderr)}");
}
var content = (Dictionary<string, object>) json["content"];
if (!content.TryGetValue("deployments", out var deploymentsObj))
{
return new List<LocalDeployment>();
}
var deploymentData = (List<object>) deploymentsObj;
return deploymentData
.OfType<Dictionary<string, object>>()
.Select(data =>
{
var id = (string) data["id"];
var name = (string) data["name"];
if (!data.TryGetValue("tag", out var tagsObj))
{
tagsObj = new List<object>();
}
var tags = (List<object>) tagsObj;
return new LocalDeployment(this, id, name, ProjectName, tags.Cast<string>().ToArray());
})
.ToList();
}
public void Dispose()
{
var result = RedirectedProcess
.Spatial("service", "stop")
.InDirectory(Common.SpatialProjectRootDir)
.RedirectOutputOptions(OutputRedirectBehaviour.None)
.RunAsync()
.Result;
if (result.ExitCode != 0)
{
Debug.LogWarning($"Failed to stop spatiald with error:\n {string.Join("\n", result.Stderr)}");
}
}
/// <summary>
/// Represents a local deployment.
/// </summary>
public struct LocalDeployment : IDisposable
{
/// <summary>
/// The ID of this deployment.
/// </summary>
public readonly string Id;
/// <summary>
/// The name of this deployment.
/// </summary>
public readonly string Name;
/// <summary>
/// The project that this deployment belongs to.
/// </summary>
public readonly string ProjectName;
/// <summary>
/// The tags that are present on this deployment.
/// </summary>
public readonly List<string> Tags;
private readonly SpatialdManager spatiald;
internal LocalDeployment(SpatialdManager spatiald, string id, string name, string projectName, params string[] tags)
{
this.spatiald = spatiald;
Id = id;
Name = name;
ProjectName = projectName;
Tags = tags.ToList();
}
/// <summary>
/// Adds the "dev_login" tag to this deployment asynchronously.
/// </summary>
/// <returns>A task which represents the underlying operation to add the tag.</returns>
/// <exception cref="InvalidOperationException">Thrown if the operation to set the tag fails.</exception>
public async Task AddDevLoginTag()
{
// TODO: Remove shim once tag functionality is added to `spot`: UTY-2212 to track.
var result = await RedirectedProcess.Command(Common.DotNetBinary)
.WithArgs("run", Id, Name, ProjectName)
.InDirectory(SpotShimPath)
.RedirectOutputOptions(OutputRedirectBehaviour.None)
.RunAsync()
.ConfigureAwait(false);
if (result.ExitCode != 0)
{
throw new InvalidOperationException($"Failed to set deployment tag with error:\n {string.Join("\n", result.Stderr)}");
}
Tags.Add("dev_login");
}
public void Dispose()
{
try
{
spatiald.StopLocalDeployment(this).Wait();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
}
}
}