-
-
Notifications
You must be signed in to change notification settings - Fork 746
Expand file tree
/
Copy pathElectronProcessActive.cs
More file actions
323 lines (276 loc) · 12 KB
/
Copy pathElectronProcessActive.cs
File metadata and controls
323 lines (276 loc) · 12 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
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
namespace ElectronNET.Runtime.Services.ElectronProcess
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using ElectronNET.Common;
using ElectronNET.Runtime.Data;
/// <summary>
/// Launches and manages the Electron app process.
/// </summary>
[Localizable(false)]
internal class ElectronProcessActive : ElectronProcessBase
{
private const string AuthTokenEnvVar = "ELECTRONNET_AUTH_TOKEN";
private const string StartupInfoEnvVar = "ELECTRONNET_STARTUP_INFO";
private readonly bool isUnpackaged;
private readonly string electronBinaryName;
private readonly string extraArguments;
private readonly int socketPort;
private ProcessRunner process;
/// <summary>Initializes a new instance of the <see cref="ElectronProcessActive"/> class.</summary>
/// <param name="isUnpackaged">The is debug.</param>
/// <param name="electronBinaryName">Name of the electron.</param>
/// <param name="extraArguments">The extraArguments.</param>
/// <param name="socketPort">The socket port.</param>
public ElectronProcessActive(bool isUnpackaged, string electronBinaryName, string extraArguments, int socketPort)
{
this.isUnpackaged = isUnpackaged;
this.electronBinaryName = electronBinaryName;
this.extraArguments = extraArguments;
this.socketPort = socketPort;
}
protected override async Task StartCore()
{
var dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
string startCmd, args, workingDir;
if (this.isUnpackaged)
{
this.CheckRuntimeIdentifier();
var electrondir = Path.Combine(dir.FullName, ".electron");
ProcessRunner chmodRunner = null;
try
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var distFolder = Path.Combine(electrondir, "node_modules", "electron", "dist");
chmodRunner = new ProcessRunner("ElectronRunner-Chmod");
chmodRunner.Run("chmod", "-R +x " + distFolder, electrondir);
await chmodRunner.WaitForExitAsync().ConfigureAwait(true);
if (chmodRunner.LastExitCode != 0)
{
throw new Exception("Failed to set executable permissions on Electron dist folder.");
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine("[StartCore]: Exception: " + chmodRunner?.StandardError);
Console.Error.WriteLine("[StartCore]: Exception: " + chmodRunner?.StandardOutput);
Console.Error.WriteLine("[StartCore]: Exception: " + ex);
}
startCmd = Path.Combine(electrondir, "node_modules", "electron", "dist", "electron");
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
startCmd = Path.Combine(electrondir, "node_modules", "electron", "dist", "Electron.app", "Contents", "MacOS", "Electron");
}
args = $"main.js -unpackeddotnet --trace-warnings -electronforcedport={this.socketPort:D} " + this.extraArguments;
workingDir = electrondir;
}
else
{
dir = dir.Parent!.Parent!;
startCmd = Path.Combine(dir.FullName, this.electronBinaryName);
args = $"-dotnetpacked -electronforcedport={this.socketPort:D} " + this.extraArguments;
workingDir = dir.FullName;
}
// Generate the auth token on the .NET side (256 bit entropy) and pass it
// to Electron via an environment variable. Electron will report the
// OS-selected port via a temporary handshake file - this avoids any
// dependency on parsing Electron's console output.
var authToken = CreateAuthToken();
var startupInfoPath = Path.Combine(
Path.GetTempPath(),
$"electronnet-startup-{Environment.ProcessId}-{Guid.NewGuid():N}.json");
// We don't await this in order to let the state transition to "Starting"
Task.Run(async () => await this.StartInternal(startCmd, args, workingDir, authToken, startupInfoPath).ConfigureAwait(false));
}
private static string CreateAuthToken()
{
var bytes = RandomNumberGenerator.GetBytes(32);
return Convert.ToHexString(bytes).ToLowerInvariant();
}
private void CheckRuntimeIdentifier()
{
var buildInfoRid = ElectronNetRuntime.BuildInfo.RuntimeIdentifier;
if (string.IsNullOrEmpty(buildInfoRid))
{
return;
}
var osPart = buildInfoRid.Split('-').First();
var mismatch = false;
switch (osPart)
{
case "win":
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
mismatch = true;
}
break;
case "linux":
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
mismatch = true;
}
break;
case "osx":
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
mismatch = true;
}
break;
case "freebsd":
if (!RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD))
{
mismatch = true;
}
break;
}
if (mismatch)
{
throw new PlatformNotSupportedException($"This Electron.NET application was built for '{buildInfoRid}'. It cannot run on this platform.");
}
}
protected override Task StopCore()
{
this.process.Cancel();
return Task.CompletedTask;
}
private async Task StartInternal(string startCmd, string args, string directoriy, string authToken, string startupInfoPath)
{
var tcs = new TaskCompletionSource();
using var cts = new CancellationTokenSource(2 * 60_000); // cancel after 2 minutes
using var _ = cts.Token.Register(() =>
{
// Time is over - let's kill the process and move on
this.process.Cancel();
// We don't want to raise exceptions here - just pass the barrier
tcs.TrySetResult();
});
void Monitor_SocketIO_Failure(object sender, EventArgs e)
{
// We don't want to raise exceptions here - just pass the barrier
if (tcs.Task.IsCompleted)
{
this.Process_Exited(sender, e);
}
else
{
tcs.TrySetResult();
}
}
try
{
Console.Error.WriteLine("[StartInternal]: startCmd: {0}", startCmd);
Console.Error.WriteLine("[StartInternal]: args: {0}", args);
this.process = new ProcessRunner("ElectronRunner");
this.process.ProcessExited += Monitor_SocketIO_Failure;
var env = new Dictionary<string, string>
{
[AuthTokenEnvVar] = authToken,
[StartupInfoEnvVar] = startupInfoPath,
};
this.process.Run(startCmd, args, directoriy, env);
// Wait for Electron to write the startup-info file (or for the process to die / timeout).
var waitTask = WaitForStartupInfoAsync(startupInfoPath, cts.Token);
var completed = await Task.WhenAny(waitTask, tcs.Task).ConfigureAwait(false);
int port = 0;
if (completed == waitTask && waitTask.Status == TaskStatus.RanToCompletion)
{
port = waitTask.Result;
}
Console.Error.WriteLine("[StartInternal]: after run:");
if (!this.process.IsRunning)
{
Console.Error.WriteLine("[StartInternal]: Process is not running: " + this.process.StandardError);
Console.Error.WriteLine("[StartInternal]: Process is not running: " + this.process.StandardOutput);
Task.Run(() => this.TransitionState(LifetimeState.Stopped));
}
else if (port > 0)
{
ElectronNetRuntime.ElectronAuthToken = authToken;
ElectronNetRuntime.ElectronSocketPort = port;
this.TransitionState(LifetimeState.Ready);
}
else
{
Console.Error.WriteLine("[StartInternal]: Did not receive Electron startup info before process exit/timeout.");
Task.Run(() => this.TransitionState(LifetimeState.Stopped));
}
}
catch (Exception ex)
{
Console.Error.WriteLine("[StartInternal]: Exception: " + this.process?.StandardError);
Console.Error.WriteLine("[StartInternal]: Exception: " + this.process?.StandardOutput);
Console.Error.WriteLine("[StartInternal]: Exception: " + ex);
throw;
}
finally
{
try
{
if (File.Exists(startupInfoPath))
{
File.Delete(startupInfoPath);
}
}
catch
{
// best effort cleanup
}
}
}
private static async Task<int> WaitForStartupInfoAsync(string startupInfoPath, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
if (File.Exists(startupInfoPath))
{
var json = await File.ReadAllTextAsync(startupInfoPath, cancellationToken).ConfigureAwait(false);
if (!string.IsNullOrWhiteSpace(json))
{
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("port", out var portElement) &&
portElement.TryGetInt32(out var port) &&
port > 0)
{
return port;
}
}
}
}
catch (JsonException)
{
// File may be partially written / racing with the writer - retry.
}
catch (IOException)
{
// Same - transient races on file access; retry.
}
try
{
await Task.Delay(50, cancellationToken).ConfigureAwait(false);
}
catch (TaskCanceledException)
{
break;
}
}
return 0;
}
private void Process_Exited(object sender, EventArgs e)
{
this.TransitionState(LifetimeState.Stopped);
}
}
}