2019-12-12 17:55:54 -08:00
|
|
|
/**
|
|
|
|
* Copyright 2017 Google Inc. All rights reserved.
|
|
|
|
* Modifications copyright (c) Microsoft Corporation.
|
|
|
|
*
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
*
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
*
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
* limitations under the License.
|
|
|
|
*/
|
|
|
|
|
|
|
|
import * as childProcess from 'child_process';
|
|
|
|
import * as readline from 'readline';
|
2020-04-01 14:42:47 -07:00
|
|
|
import * as removeFolder from 'rimraf';
|
|
|
|
import * as stream from 'stream';
|
2020-08-24 06:51:51 -07:00
|
|
|
import { helper } from './helper';
|
|
|
|
import { Progress } from './progress';
|
|
|
|
import * as types from './types';
|
2020-09-06 21:36:22 -07:00
|
|
|
import { isUnderTest } from '../utils/utils';
|
2019-12-12 17:55:54 -08:00
|
|
|
|
2020-05-22 07:03:42 -07:00
|
|
|
export type Env = {[key: string]: string | number | boolean | undefined};
|
|
|
|
|
2019-12-12 17:55:54 -08:00
|
|
|
export type LaunchProcessOptions = {
|
|
|
|
executablePath: string,
|
|
|
|
args: string[],
|
2020-05-22 07:03:42 -07:00
|
|
|
env?: Env,
|
2019-12-12 17:55:54 -08:00
|
|
|
|
|
|
|
handleSIGINT?: boolean,
|
|
|
|
handleSIGTERM?: boolean,
|
|
|
|
handleSIGHUP?: boolean,
|
|
|
|
pipe?: boolean,
|
2020-08-31 08:43:14 -07:00
|
|
|
pipeStdin?: boolean,
|
2020-05-22 16:06:00 -07:00
|
|
|
tempDirectories: string[],
|
2020-01-08 13:55:38 -08:00
|
|
|
|
2020-05-11 14:42:13 -07:00
|
|
|
cwd?: string,
|
|
|
|
|
2020-01-08 13:55:38 -08:00
|
|
|
// Note: attemptToGracefullyClose should reject if it does not close the browser.
|
|
|
|
attemptToGracefullyClose: () => Promise<any>,
|
2020-05-27 19:59:03 -07:00
|
|
|
onExit: (exitCode: number | null, signal: string | null) => void,
|
2020-05-29 14:39:34 -07:00
|
|
|
progress: Progress,
|
2019-12-12 17:55:54 -08:00
|
|
|
};
|
|
|
|
|
2020-04-02 17:56:14 -07:00
|
|
|
type LaunchResult = {
|
|
|
|
launchedProcess: childProcess.ChildProcess,
|
|
|
|
gracefullyClose: () => Promise<void>,
|
2020-05-27 19:59:03 -07:00
|
|
|
kill: () => Promise<void>,
|
2020-04-02 17:56:14 -07:00
|
|
|
};
|
2020-01-08 13:55:38 -08:00
|
|
|
|
2020-07-17 16:14:23 -07:00
|
|
|
const gracefullyCloseSet = new Set<() => Promise<void>>();
|
|
|
|
|
|
|
|
export async function gracefullyCloseAll() {
|
|
|
|
await Promise.all(Array.from(gracefullyCloseSet).map(gracefullyClose => gracefullyClose().catch(e => {})));
|
|
|
|
}
|
|
|
|
|
2020-01-08 13:55:38 -08:00
|
|
|
export async function launchProcess(options: LaunchProcessOptions): Promise<LaunchResult> {
|
2020-06-08 21:45:35 -07:00
|
|
|
const cleanup = () => helper.removeFolders(options.tempDirectories);
|
2020-05-22 16:06:00 -07:00
|
|
|
|
2020-05-29 14:39:34 -07:00
|
|
|
const progress = options.progress;
|
2020-02-07 11:48:55 -08:00
|
|
|
const stdio: ('ignore' | 'pipe')[] = options.pipe ? ['ignore', 'pipe', 'pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'];
|
2020-08-31 08:43:14 -07:00
|
|
|
if (options.pipeStdin)
|
|
|
|
stdio[0] = 'pipe';
|
2020-08-17 14:12:31 -07:00
|
|
|
progress.log(`<launching> ${options.executablePath} ${options.args.join(' ')}`);
|
2019-12-12 17:55:54 -08:00
|
|
|
const spawnedProcess = childProcess.spawn(
|
|
|
|
options.executablePath,
|
|
|
|
options.args,
|
|
|
|
{
|
|
|
|
// On non-windows platforms, `detached: true` makes child process a leader of a new
|
|
|
|
// process group, making it possible to kill child process tree with `.kill(-pid)` command.
|
|
|
|
// @see https://nodejs.org/api/child_process.html#child_process_options_detached
|
|
|
|
detached: process.platform !== 'win32',
|
2020-04-23 14:45:57 -07:00
|
|
|
env: (options.env as {[key: string]: string}),
|
2020-05-11 14:42:13 -07:00
|
|
|
cwd: options.cwd,
|
|
|
|
stdio,
|
2019-12-12 17:55:54 -08:00
|
|
|
}
|
|
|
|
);
|
|
|
|
if (!spawnedProcess.pid) {
|
2020-05-22 16:06:00 -07:00
|
|
|
let failed: (e: Error) => void;
|
|
|
|
const failedPromise = new Promise<Error>((f, r) => failed = f);
|
2019-12-12 17:55:54 -08:00
|
|
|
spawnedProcess.once('error', error => {
|
2020-05-22 16:06:00 -07:00
|
|
|
failed(new Error('Failed to launch browser: ' + error));
|
2019-12-12 17:55:54 -08:00
|
|
|
});
|
2020-05-22 16:06:00 -07:00
|
|
|
return cleanup().then(() => failedPromise).then(e => Promise.reject(e));
|
2019-12-12 17:55:54 -08:00
|
|
|
}
|
2020-08-17 14:12:31 -07:00
|
|
|
progress.log(`<launched> pid=${spawnedProcess.pid}`);
|
2019-12-12 17:55:54 -08:00
|
|
|
|
2020-03-23 15:08:02 -07:00
|
|
|
const stdout = readline.createInterface({ input: spawnedProcess.stdout });
|
|
|
|
stdout.on('line', (data: string) => {
|
2020-08-17 14:12:31 -07:00
|
|
|
progress.log('[out] ' + data);
|
2020-03-23 15:08:02 -07:00
|
|
|
});
|
|
|
|
|
|
|
|
const stderr = readline.createInterface({ input: spawnedProcess.stderr });
|
|
|
|
stderr.on('line', (data: string) => {
|
2020-08-17 14:12:31 -07:00
|
|
|
progress.log('[err] ' + data);
|
2020-03-23 15:08:02 -07:00
|
|
|
});
|
2019-12-12 17:55:54 -08:00
|
|
|
|
|
|
|
let processClosed = false;
|
2020-05-20 14:58:27 -07:00
|
|
|
let fulfillClose = () => {};
|
2020-05-27 19:59:03 -07:00
|
|
|
const waitForClose = new Promise<void>(f => fulfillClose = f);
|
2020-05-20 14:58:27 -07:00
|
|
|
let fulfillCleanup = () => {};
|
2020-05-27 19:59:03 -07:00
|
|
|
const waitForCleanup = new Promise<void>(f => fulfillCleanup = f);
|
2020-05-20 14:58:27 -07:00
|
|
|
spawnedProcess.once('exit', (exitCode, signal) => {
|
2020-08-17 14:12:31 -07:00
|
|
|
progress.log(`<process did exit: exitCode=${exitCode}, signal=${signal}>`);
|
2020-05-20 14:58:27 -07:00
|
|
|
processClosed = true;
|
|
|
|
helper.removeEventListeners(listeners);
|
2020-07-17 16:14:23 -07:00
|
|
|
gracefullyCloseSet.delete(gracefullyClose);
|
2020-05-27 19:59:03 -07:00
|
|
|
options.onExit(exitCode, signal);
|
2020-05-20 14:58:27 -07:00
|
|
|
fulfillClose();
|
2020-05-22 16:06:00 -07:00
|
|
|
// Cleanup as process exits.
|
|
|
|
cleanup().then(fulfillCleanup);
|
2019-12-12 17:55:54 -08:00
|
|
|
});
|
|
|
|
|
|
|
|
const listeners = [ helper.addEventListener(process, 'exit', killProcess) ];
|
2020-01-28 13:07:53 -08:00
|
|
|
if (options.handleSIGINT) {
|
|
|
|
listeners.push(helper.addEventListener(process, 'SIGINT', () => {
|
2020-07-30 10:22:28 -07:00
|
|
|
gracefullyClose().then(() => {
|
|
|
|
// Give tests a chance to dispatch any async calls.
|
2020-09-06 21:36:22 -07:00
|
|
|
if (isUnderTest())
|
2020-07-30 10:22:28 -07:00
|
|
|
setTimeout(() => process.exit(130), 0);
|
|
|
|
else
|
|
|
|
process.exit(130);
|
|
|
|
});
|
2020-01-28 13:07:53 -08:00
|
|
|
}));
|
|
|
|
}
|
2019-12-12 17:55:54 -08:00
|
|
|
if (options.handleSIGTERM)
|
|
|
|
listeners.push(helper.addEventListener(process, 'SIGTERM', gracefullyClose));
|
|
|
|
if (options.handleSIGHUP)
|
|
|
|
listeners.push(helper.addEventListener(process, 'SIGHUP', gracefullyClose));
|
2020-07-17 16:14:23 -07:00
|
|
|
gracefullyCloseSet.add(gracefullyClose);
|
2019-12-12 17:55:54 -08:00
|
|
|
|
2020-01-28 13:07:53 -08:00
|
|
|
let gracefullyClosing = false;
|
2019-12-12 17:55:54 -08:00
|
|
|
async function gracefullyClose(): Promise<void> {
|
2020-07-17 16:14:23 -07:00
|
|
|
gracefullyCloseSet.delete(gracefullyClose);
|
2020-01-08 13:55:38 -08:00
|
|
|
// We keep listeners until we are done, to handle 'exit' and 'SIGINT' while
|
|
|
|
// asynchronously closing to prevent zombie processes. This might introduce
|
2020-01-28 13:07:53 -08:00
|
|
|
// reentrancy to this function, for example user sends SIGINT second time.
|
|
|
|
// In this case, let's forcefully kill the process.
|
|
|
|
if (gracefullyClosing) {
|
2020-08-17 14:12:31 -07:00
|
|
|
progress.log(`<forecefully close>`);
|
2020-01-28 13:07:53 -08:00
|
|
|
killProcess();
|
2020-05-20 14:58:27 -07:00
|
|
|
await waitForClose; // Ensure the process is dead and we called options.onkill.
|
2020-01-08 13:55:38 -08:00
|
|
|
return;
|
2020-01-28 13:07:53 -08:00
|
|
|
}
|
2020-01-08 13:55:38 -08:00
|
|
|
gracefullyClosing = true;
|
2020-08-17 14:12:31 -07:00
|
|
|
progress.log(`<gracefully close start>`);
|
2020-04-02 16:57:12 -07:00
|
|
|
await options.attemptToGracefullyClose().catch(() => killProcess());
|
2020-05-20 14:58:27 -07:00
|
|
|
await waitForCleanup; // Ensure the process is dead and we have cleaned up.
|
2020-08-17 14:12:31 -07:00
|
|
|
progress.log(`<gracefully close end>`);
|
2019-12-12 17:55:54 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// This method has to be sync to be used as 'exit' event handler.
|
|
|
|
function killProcess() {
|
2020-08-17 14:12:31 -07:00
|
|
|
progress.log(`<kill>`);
|
2019-12-12 17:55:54 -08:00
|
|
|
helper.removeEventListeners(listeners);
|
|
|
|
if (spawnedProcess.pid && !spawnedProcess.killed && !processClosed) {
|
2020-01-22 17:42:10 -08:00
|
|
|
// Force kill the browser.
|
2019-12-12 17:55:54 -08:00
|
|
|
try {
|
|
|
|
if (process.platform === 'win32')
|
|
|
|
childProcess.execSync(`taskkill /pid ${spawnedProcess.pid} /T /F`);
|
|
|
|
else
|
|
|
|
process.kill(-spawnedProcess.pid, 'SIGKILL');
|
|
|
|
} catch (e) {
|
|
|
|
// the process might have already stopped
|
|
|
|
}
|
|
|
|
}
|
|
|
|
try {
|
2020-05-22 16:06:00 -07:00
|
|
|
// Attempt to remove temporary directories to avoid littering.
|
|
|
|
for (const dir of options.tempDirectories)
|
|
|
|
removeFolder.sync(dir);
|
2019-12-12 17:55:54 -08:00
|
|
|
} catch (e) { }
|
|
|
|
}
|
2020-01-28 13:07:53 -08:00
|
|
|
|
2020-05-27 19:59:03 -07:00
|
|
|
function killAndWait() {
|
|
|
|
killProcess();
|
|
|
|
return waitForCleanup;
|
|
|
|
}
|
|
|
|
|
|
|
|
return { launchedProcess: spawnedProcess, gracefullyClose, kill: killAndWait };
|
2019-12-12 17:55:54 -08:00
|
|
|
}
|
|
|
|
|
2020-05-29 14:39:34 -07:00
|
|
|
export function waitForLine(progress: Progress, process: childProcess.ChildProcess, inputStream: stream.Readable, regex: RegExp): Promise<RegExpMatchArray> {
|
2019-12-12 17:55:54 -08:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const rl = readline.createInterface({ input: inputStream });
|
2020-07-10 16:04:19 -07:00
|
|
|
const failError = new Error('Process failed to launch!');
|
2019-12-12 17:55:54 -08:00
|
|
|
const listeners = [
|
|
|
|
helper.addEventListener(rl, 'line', onLine),
|
2020-07-10 16:04:19 -07:00
|
|
|
helper.addEventListener(rl, 'close', reject.bind(null, failError)),
|
|
|
|
helper.addEventListener(process, 'exit', reject.bind(null, failError)),
|
|
|
|
helper.addEventListener(process, 'error', reject.bind(null, failError))
|
2019-12-12 17:55:54 -08:00
|
|
|
];
|
|
|
|
|
2020-06-04 16:43:48 -07:00
|
|
|
progress.cleanupWhenAborted(cleanup);
|
2019-12-12 17:55:54 -08:00
|
|
|
|
|
|
|
function onLine(line: string) {
|
|
|
|
const match = line.match(regex);
|
|
|
|
if (!match)
|
|
|
|
return;
|
|
|
|
cleanup();
|
|
|
|
resolve(match);
|
|
|
|
}
|
|
|
|
|
|
|
|
function cleanup() {
|
|
|
|
helper.removeEventListeners(listeners);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2020-08-18 09:37:40 -07:00
|
|
|
|
|
|
|
export function envArrayToObject(env: types.EnvArray): Env {
|
|
|
|
const result: Env = {};
|
|
|
|
for (const { name, value } of env)
|
|
|
|
result[name] = value;
|
|
|
|
return result;
|
|
|
|
}
|