/
nodeLauncherBase.ts
540 lines (468 loc) · 15.4 KB
/
nodeLauncherBase.ts
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import * as fs from 'fs';
import { inject, injectable } from 'inversify';
import * as net from 'net';
import * as os from 'os';
import * as path from 'path';
import { getSourceSuffix } from '../../adapter/templates';
import Cdp from '../../cdp/api';
import Connection from '../../cdp/connection';
import { RawPipeTransport } from '../../cdp/rawPipeTransport';
import { CancellationTokenSource } from '../../common/cancellation';
import { AutoAttachMode } from '../../common/contributionUtils';
import { ObservableMap } from '../../common/datastructure/observableMap';
import { EnvironmentVars } from '../../common/environmentVars';
import { EventEmitter } from '../../common/events';
import { ILogger, LogTag } from '../../common/logging';
import { once } from '../../common/objUtils';
import { findInPath, forceForwardSlashes } from '../../common/pathUtils';
import { delay } from '../../common/promiseUtil';
import { AnyLaunchConfiguration, AnyNodeConfiguration } from '../../configuration';
import { cannotLoadEnvironmentVars } from '../../dap/errors';
import { ProtocolError } from '../../dap/protocolError';
import {
ILaunchContext,
ILauncher,
ILaunchResult,
IStopMetadata,
ITarget,
} from '../../targets/targets';
import { ITelemetryReporter } from '../../telemetry/telemetryReporter';
import { IBootloaderEnvironment, IBootloaderInfo } from './bootloader/environment';
import { bootloaderDefaultPath } from './bundlePaths';
import {
Capability,
INodeBinaryProvider,
NodeBinary,
NodeBinaryProvider,
} from './nodeBinaryProvider';
import { NodeSourcePathResolver } from './nodeSourcePathResolver';
import { INodeTargetLifecycleHooks, NodeTarget } from './nodeTarget';
import { IProgram } from './program';
import { FSUtils } from '../../common/fsUtils';
import { IFsUtils } from '../../common/fsUtils';
/**
* Telemetry received from the nested process.
*/
export interface IProcessTelemetry {
/**
* Process working directory.
*/
cwd: string;
/**
* Target process ID.
*/
processId: number;
/**
* Process node version.
*/
nodeVersion: string;
/**
* CPU architecture.
*/
architecture: string;
}
/**
* Data stored for a currently running debug session within the Node launcher.
*/
export interface IRunData<T> {
server: net.Server;
serverAddress: string;
pathResolver: NodeSourcePathResolver;
context: ILaunchContext;
logger: ILogger;
params: T;
}
let counter = 0;
@injectable()
export abstract class NodeLauncherBase<T extends AnyNodeConfiguration> implements ILauncher {
/**
* Data set while a debug session is running.
*/
protected run?: IRunData<T>;
/**
* Attached server connections. Tracked so they can be torn down readily.
*/
private serverConnections = new Set<Connection>();
/**
* Target list.
*/
private readonly targets = new ObservableMap<string, NodeTarget>();
/**
* Underlying emitter fired when sessions terminate. Listened to by the
* binder and used to trigger a `terminate` message on the DAP.
*/
private onTerminatedEmitter = new EventEmitter<IStopMetadata>();
/**
* @inheritdoc
*/
public readonly onTerminated = this.onTerminatedEmitter.event;
/**
* @inheritdoc
*/
public readonly onTargetListChanged = this.targets.onChanged;
/**
* The currently running program. Set to undefined if there's no process
* running.
*/
protected program?: IProgram;
/**
* Bootloader file, if created.
*/
private bootloaderFile = once(this.getBootloaderFile.bind(this));
constructor(
@inject(INodeBinaryProvider) private readonly pathProvider: NodeBinaryProvider,
@inject(ILogger) protected readonly logger: ILogger,
@inject(FSUtils) protected readonly fsUtils: IFsUtils,
) {}
/**
* @inheritdoc
*/
public async launch(
params: AnyLaunchConfiguration,
context: ILaunchContext,
): Promise<ILaunchResult> {
const resolved = this.resolveParams(params);
if (!resolved) {
return { blockSessionTermination: false };
}
this._stopServer(); // clear any ongoing run
const { server, pipe } = await this._startServer(context.telemetryReporter);
const logger = this.logger.forTarget();
const run = (this.run = {
server,
serverAddress: pipe,
params: resolved,
context,
logger,
pathResolver: new NodeSourcePathResolver(
this.fsUtils,
{
resolveSourceMapLocations: resolved.resolveSourceMapLocations,
basePath: resolved.cwd,
sourceMapOverrides: resolved.sourceMapPathOverrides,
remoteRoot: resolved.remoteRoot,
localRoot: resolved.localRoot,
},
logger,
),
});
await this.launchProgram(run);
return { blockSessionTermination: true };
}
/**
* @inheritdoc
*/
public async terminate(): Promise<void> {
if (this.program) {
await this.program.stop();
} else {
this.onProgramTerminated({ code: 0, killed: true });
}
}
/**
* @inheritdoc
*/
public async disconnect(): Promise<void> {
await this.terminate();
}
/**
* Restarts the ongoing program.
*/
public async restart(): Promise<void> {
if (!this.run) {
return;
}
// Clear the program so that termination logic doesn't run.
const program = this.program;
if (program) {
this.program = undefined;
await program.stop();
const closeOk = await Promise.race([
delay(2000).then(() => false),
Promise.all([...this.serverConnections].map(c => new Promise(r => c.onDisconnected(r)))),
]);
if (!closeOk) {
this.logger.warn(LogTag.RuntimeLaunch, 'Timeout waiting for server connections to close');
this.closeAllConnections();
}
}
// relaunch the program, releasing the initial cancellation token:
const cts = CancellationTokenSource.withTimeout(this.run.params.timeout);
await this.launchProgram({
...this.run,
context: {
...this.run.context,
cancellationToken: cts.token,
},
});
}
public targetList(): ITarget[] {
return [...this.targets.value()];
}
/**
* @inheritdoc
*/
public dispose() {
this._stopServer();
}
/**
* Returns the params type if they can be launched by this launcher,
* or undefined if they cannot.
*/
protected abstract resolveParams(params: AnyLaunchConfiguration): T | undefined;
/**
* Launches the program. Called after the server is running and upon restart.
*/
protected abstract launchProgram(runData: IRunData<T>): Promise<void>;
/**
* Method that should be called when the program from launchProgram() exits.
* Emits a stop to the client and tears down the server.
*/
protected onProgramTerminated(result: IStopMetadata) {
this.onTerminatedEmitter.fire(result);
this._stopServer();
this.program = undefined;
}
/**
* Resolves and validates the path to the Node binary as specified in
* the params.
*/
protected resolveNodePath(params: T, executable = 'node') {
return this.pathProvider.resolveAndValidate(
EnvironmentVars.merge(process.env, this.getConfiguredEnvironment(params)),
executable,
params.nodeVersionHint,
);
}
/**
* Returns the user-configured portion of the environment variables.
*/
protected getConfiguredEnvironment(params: T) {
let baseEnv = EnvironmentVars.empty;
// read environment variables from any specified file
if (params.envFile) {
try {
baseEnv = baseEnv.merge(readEnvFile(params.envFile));
} catch (e) {
throw new ProtocolError(cannotLoadEnvironmentVars(e.message));
}
}
return baseEnv.merge(params.env);
}
/**
* Gets the environment variables for the session.
*/
protected async resolveEnvironment(
{ params, serverAddress }: IRunData<T>,
binary: NodeBinary,
additionalOptions?: Partial<IBootloaderInfo>,
) {
const baseEnv = this.getConfiguredEnvironment(params);
const bootloader = await this.bootloaderFile(params.cwd, binary);
const bootloaderInfo: IBootloaderInfo = {
inspectorIpc: serverAddress,
ppid: undefined,
deferredMode: false,
// todo: look at reimplementing the filter
// NODE_INSPECTOR_WAIT_FOR_DEBUGGER: this._launchParams!.nodeFilter || '',
waitForDebugger: '',
// Supply some node executable for running top-level watchdog in Electron
// environments. Bootloader will replace this with actual node executable used if any.
execPath: await findInPath(fs.promises, 'node', process.env),
onlyEntrypoint: !params.autoAttachChildProcesses,
autoAttachMode: AutoAttachMode.Always,
...additionalOptions,
};
const env = {
// Require our bootloader first, to run it before any other bootloader
// we could have injected in the parent process.
NODE_OPTIONS: `--require ${bootloader.interpolatedPath}`,
VSCODE_INSPECTOR_OPTIONS: JSON.stringify(bootloaderInfo),
ELECTRON_RUN_AS_NODE: null,
} as IBootloaderEnvironment;
const existingOpts = baseEnv.lookup('NODE_OPTIONS');
if (existingOpts) {
env.NODE_OPTIONS += ` ${existingOpts}`;
}
return baseEnv.merge({ ...env });
}
/**
* Logic run when a thread is created.
*/
protected createLifecycle(
// eslint-disable-next-line
_cdp: Cdp.Api,
// eslint-disable-next-line
_run: IRunData<T>,
// eslint-disable-next-line
_target: Cdp.Target.TargetInfo,
): INodeTargetLifecycleHooks {
return {};
}
protected async _startServer(telemetryReporter: ITelemetryReporter) {
const pipePrefix = process.platform === 'win32' ? '\\\\.\\pipe\\' : os.tmpdir();
const pipe = path.join(pipePrefix, `node-cdp.${process.pid}-${++counter}.sock`);
const server = await new Promise<net.Server>((resolve, reject) => {
const s = net
.createServer(socket => this._startSession(socket, telemetryReporter))
.on('error', reject)
.listen(pipe, () => resolve(s));
});
return { pipe, server };
}
protected _stopServer() {
this.run?.server.close();
this.run = undefined;
this.bootloaderFile.value?.then(f => f.dispose());
this.bootloaderFile.forget();
this.closeAllConnections();
}
protected closeAllConnections() {
this.serverConnections.forEach(c => c.close());
this.serverConnections.clear();
}
protected async _startSession(socket: net.Socket, telemetryReporter: ITelemetryReporter) {
if (!this.run) {
return;
}
const { connection, cdp, targetInfo } = await this.acquireTarget(
socket,
telemetryReporter,
this.run.logger,
);
if (!this.run) {
// if we aren't running a session, discard the socket.
socket.destroy();
return;
}
const target = new NodeTarget(
this.fsUtils,
this.run.params,
this.run.pathResolver,
this.run.context.targetOrigin,
connection,
cdp,
targetInfo,
this.run.logger,
this.createLifecycle(cdp, this.run, targetInfo),
);
target.setParent(targetInfo.openerId ? this.targets.get(targetInfo.openerId) : undefined);
this.targets.add(targetInfo.targetId, target);
target.onDisconnect(() => this.targets.remove(targetInfo.targetId));
}
/**
* Acquires the CDP session and target info from the connecting socket.
*/
protected async acquireTarget(
socket: net.Socket,
rawTelemetryReporter: ITelemetryReporter,
logger: ILogger,
) {
const connection = new Connection(
new RawPipeTransport(logger, socket),
logger,
rawTelemetryReporter,
);
this.serverConnections.add(connection);
connection.onDisconnected(() => this.serverConnections.delete(connection));
const cdp = connection.rootSession();
const { targetInfo } = await new Promise<Cdp.Target.TargetCreatedEvent>(f =>
cdp.Target.on('targetCreated', f),
);
return { targetInfo, cdp, connection, logger };
}
/**
* Returns the file from which to load our bootloader. We need to do this in
* since Node does not support paths with spaces in them < 13 (nodejs/node#12971),
* so if our installation path has spaces, we need to fall back somewhere.
*/
protected async getBootloaderFile(cwd: string | undefined, binary: NodeBinary) {
const targetPath = forceForwardSlashes(bootloaderDefaultPath);
// 1. If the path doesn't have a space, we're OK to use it.
if (!targetPath.includes(' ')) {
return { interpolatedPath: targetPath, dispose: () => undefined };
}
// 1.5. If we can otherwise use spaces in the path, quote and return it.
if (binary.has(Capability.UseSpacesInRequirePath)) {
return { interpolatedPath: `"${targetPath}"`, dispose: () => undefined };
}
// 2. Try the tmpdir, if it's space-free.
const contents = `require(${JSON.stringify(targetPath)})`;
if (!os.tmpdir().includes(' ') || !cwd) {
const tmpPath = path.join(os.tmpdir(), 'vscode-js-debug-bootloader.js');
await fs.promises.writeFile(tmpPath, contents);
return { interpolatedPath: tmpPath, dispose: () => undefined };
}
// 3. Worst case, write into the cwd. This is messy, but we have few options.
const nearFilename = '.vscode-js-debug-bootloader.js';
const nearPath = path.join(cwd, nearFilename);
await fs.promises.writeFile(nearPath, contents);
return {
interpolatedPath: `./${nearFilename}`,
dispose: () => fs.unlinkSync(nearPath),
};
}
/**
* Reads telemetry from the process.
*/
protected async gatherTelemetryFromCdp(
cdp: Cdp.Api,
run: IRunData<T>,
): Promise<IProcessTelemetry | void> {
const telemetry = await cdp.Runtime.evaluate({
contextId: 1,
returnByValue: true,
expression:
`typeof process === 'undefined' ? 'process not defined' : ({ processId: process.pid, nodeVersion: process.version, architecture: process.arch })` +
getSourceSuffix(),
});
if (!this.program) {
return; // shut down
}
if (!telemetry || !telemetry.result.value) {
this.logger.error(LogTag.RuntimeTarget, 'Undefined result getting telemetry');
return;
}
if (typeof telemetry.result.value !== 'object') {
this.logger.info(LogTag.RuntimeTarget, 'Process not yet defined, will retry');
await delay(10);
return this.gatherTelemetryFromCdp(cdp, run);
}
const result = telemetry.result.value as IProcessTelemetry;
run.context.telemetryReporter.report('nodeRuntime', {
version: result.nodeVersion,
arch: result.architecture,
});
this.program.gotTelemetery(result);
return result;
}
}
function readEnvFile(file: string): { [key: string]: string } {
if (!fs.existsSync(file)) {
return {};
}
const buffer = stripBOM(fs.readFileSync(file, 'utf8'));
const env: { [key: string]: string } = {};
for (const line of buffer.split('\n')) {
const r = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/);
if (!r) {
continue;
}
let value = r[2] || '';
// .env variables never overwrite existing variables (see #21169)
if (value.length > 0 && value.charAt(0) === '"' && value.charAt(value.length - 1) === '"') {
value = value.replace(/\\n/gm, '\n');
}
env[r[1]] = value.replace(/(^['"]|['"]$)/g, '');
}
return env;
}
function stripBOM(s: string): string {
if (s && s[0] === '\uFEFF') {
s = s.substr(1);
}
return s;
}