This repository has been archived by the owner on Jan 18, 2022. It is now read-only.
/
LocalLaunch.cs
307 lines (254 loc) · 11.6 KB
/
LocalLaunch.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
using Improbable.Gdk.Tools.MiniJSON;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace Improbable.Gdk.Tools
{
public static class LocalLaunch
{
private const string InspectorUrl = "http://localhost:21000/inspector";
private static readonly string DefaultLogFileName
= Path.GetFullPath(Path.Combine(Common.SpatialProjectRootDir, "logs", "*unityclient.log"));
private static readonly string
BuildPath = Path.GetFullPath(Path.Combine(Common.SpatialProjectRootDir, "build", "assembly", "worker"));
private static readonly string ClientConfigFilename = "spatialos.UnityClient.worker.json";
// Windows: The exit code is 0xc000013a when the user closes the console window, or presses Ctrl+C.
private const int WindowsCtrlCExitCode = -1073741510;
// Unix-like: The exit code is 128 + SIGINT (2).
private const int UnixSigIntExitCode = 128 + 2;
[MenuItem("SpatialOS/Build worker configs", false, MenuPriorities.BuildWorkerConfigs)]
private static void BuildConfigMenu()
{
Debug.Log("Building worker configs...");
EditorApplication.delayCall += BuildConfig;
}
[MenuItem("SpatialOS/Local launch %l", false, MenuPriorities.LocalLaunch)]
private static void LaunchMenu()
{
GdkToolsConfiguration toolsConfig = GdkToolsConfiguration.GetOrCreateInstance();
if (!File.Exists(toolsConfig.CustomSnapshotPath))
{
Debug.LogError($"Snapshot {toolsConfig.CustomSnapshotPath} not found. Make sure the file exists and it has not been moved or renamed");
return;
}
Debug.Log($"Launching SpatialOS locally with snapshot {toolsConfig.CustomSnapshotPath}.");
EditorApplication.delayCall += LaunchLocalDeployment;
}
[MenuItem("SpatialOS/Launch standalone client", false, MenuPriorities.LaunchStandaloneClient)]
private static void LaunchStandaloneClient()
{
Debug.Log("Launching a standalone client");
EditorApplication.delayCall += LaunchClient;
}
[MenuItem("SpatialOS/Open inspector", false, MenuPriorities.OpenInspector)]
private static void OpenInspector()
{
Application.OpenURL(InspectorUrl);
}
public static void BuildConfig()
{
using (new ShowProgressBarScope("Building worker configs..."))
{
// Run from the root of the project to build all available worker configs.
RedirectedProcess
.Command(Common.SpatialBinary)
.WithArgs("build", "build-config", "--json_output")
.InDirectory(Common.SpatialProjectRootDir)
.Run();
}
}
public static void LaunchClient()
{
var command = Common.SpatialBinary;
var commandArgs = "local worker launch UnityClient default";
var unityClientZipName = "UnityClient@Windows.zip";
if (Application.platform == RuntimePlatform.OSXEditor)
{
command = "osascript";
commandArgs = $@"-e 'tell application ""Terminal""
activate
do script ""cd {Common.SpatialProjectRootDir} && {Common.SpatialBinary} {commandArgs}""
end tell'";
unityClientZipName = "UnityClient@Mac.zip";
}
var processInfo = new ProcessStartInfo(command, commandArgs)
{
CreateNoWindow = false,
UseShellExecute = true,
WorkingDirectory = Common.SpatialProjectRootDir
};
var process = Process.Start(processInfo);
if (process == null)
{
Debug.LogError("Failed to start a standalone client locally.");
return;
}
process.EnableRaisingEvents = true;
process.Exited += (sender, args) =>
{
// N.B. This callback is run on a different thread.
if (process.ExitCode == 0)
{
return;
}
var latestLogFile = GetClientLogFileFullPath();
var latestClientBuild = Path.GetFullPath(Path.Combine(BuildPath, unityClientZipName));
if (!File.Exists(latestClientBuild))
{
Debug.LogError($"Local client build missing. Couldn't find the Unity Client at {latestClientBuild}.");
return;
}
if (!File.Exists(latestLogFile))
{
Debug.LogError($"Could not find a standalone client log file {latestLogFile}.");
return;
}
var message = $"For more information, check the Unity Standalone Client local launch logfile: {latestLogFile}";
if (WasProcessKilled(process))
{
Debug.Log(message);
}
else
{
Debug.LogError($"Errors occured - {message}");
}
process.Dispose();
process = null;
};
}
private static string GetClientLogFileFullPath()
{
try
{
var logConfigPath = Path.Combine(Common.SpatialProjectRootDir, "workers", "unity");
var configFileJson = File.ReadAllText(Path.Combine(logConfigPath, ClientConfigFilename));
var configFileJsonDeserialized = Json.Deserialize(configFileJson);
var currentOS = Application.platform == RuntimePlatform.OSXEditor ? "macos" : "windows";
Dictionary<string, object> partialJsonDict;
if (!configFileJsonDeserialized.TryGetValue("external", out var externalValue))
{
Debug.LogError($"Config file {ClientConfigFilename} doesn't contain key 'external'.");
return DefaultLogFileName;
}
partialJsonDict = externalValue as Dictionary<string, object>;
if (!partialJsonDict.TryGetValue("default", out var defaultValue))
{
Debug.LogError($"Config file {ClientConfigFilename} doesn't contain key 'default' within 'external'.");
return DefaultLogFileName;
}
partialJsonDict = defaultValue as Dictionary<string, object>;
if (!partialJsonDict.TryGetValue(currentOS, out var currentOSValue))
{
Debug.LogError($"Config file {ClientConfigFilename} doesn't contain key '{currentOS}' within 'external' -> 'default'.");
return DefaultLogFileName;
}
partialJsonDict = currentOSValue as Dictionary<string, object>;
if (!partialJsonDict.TryGetValue("arguments", out var argumentsValue))
{
Debug.LogError($"Config file {ClientConfigFilename} doesn't contain key 'arguments' within 'external' -> 'default' -> '{currentOS}'.");
return DefaultLogFileName;
}
var arguments = (List<object>) argumentsValue;
var logFileArg = arguments.SkipWhile(arg => !string.Equals(arg, "-logfile")).FirstOrDefault(arg => !string.Equals(arg, "-logfile"));
// Logger file not found - using default one
if (logFileArg == null)
{
Debug.LogError($"Config file {ClientConfigFilename} doesn't contain '-logfile' argument within 'external' -> 'default' -> '{currentOS}' -> arguments.");
return DefaultLogFileName;
}
var logFileName = Path.GetFullPath(Path.Combine(logConfigPath, (string) logFileArg));
return logFileName;
}
catch (System.Exception e)
{
Debug.LogError(e.ToString());
return DefaultLogFileName;
}
}
public static void LaunchLocalDeployment()
{
BuildConfig();
GdkToolsConfiguration toolsConfig = GdkToolsConfiguration.GetOrCreateInstance();
var command = Common.SpatialBinary;
#if UNITY_EDITOR_OSX
var commandArgs = $"local launch --enable_pre_run_check=false --snapshot '{toolsConfig.CustomSnapshotPath}'";
#else
var commandArgs = $"local launch --enable_pre_run_check=false --snapshot \"{toolsConfig.CustomSnapshotPath}\"";
#endif
var runtimeIp = EditorPrefs.GetString(Common.RuntimeIpEditorPrefKey);
if (!string.IsNullOrEmpty(runtimeIp))
{
commandArgs = $"{commandArgs} --runtime_ip={runtimeIp}";
}
if (Application.platform == RuntimePlatform.OSXEditor)
{
command = "osascript";
commandArgs = $@"-e 'tell application ""Terminal""
activate
do script ""cd {Common.SpatialProjectRootDir} && {Common.SpatialBinary} {commandArgs}""
end tell'";
}
var processInfo = new ProcessStartInfo(command, commandArgs)
{
CreateNoWindow = false,
UseShellExecute = true,
WorkingDirectory = Common.SpatialProjectRootDir
};
var process = Process.Start(processInfo);
if (process == null)
{
Debug.LogError("Failed to start SpatialOS locally.");
return;
}
process.EnableRaisingEvents = true;
process.Exited += (sender, args) =>
{
// N.B. This callback is run on a different thread.
if (process.ExitCode == 0)
{
return;
}
var logPath = Path.Combine(Common.SpatialProjectRootDir, "logs");
var latestLogFile = Directory.GetFiles(logPath, "spatial_*.log")
.Select(f => new FileInfo(f))
.OrderBy(f => f.LastWriteTimeUtc).LastOrDefault();
if (latestLogFile == null)
{
Debug.LogError($"Could not find a spatial log file in {logPath}.");
return;
}
var message = $"For more information, check the spatial local launch logfile: {latestLogFile.FullName}";
if (WasProcessKilled(process))
{
Debug.Log(message);
}
else
{
Debug.LogError($"Errors occured - {message}");
}
process.Dispose();
process = null;
};
}
private static bool WasProcessKilled(Process process)
{
if (process == null)
{
return false;
}
switch (Application.platform)
{
case RuntimePlatform.WindowsEditor:
return process.ExitCode == WindowsCtrlCExitCode;
case RuntimePlatform.OSXEditor:
case RuntimePlatform.LinuxEditor:
return process.ExitCode == UnixSigIntExitCode;
}
return false;
}
}
}