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';
|
2020-04-20 23:24:53 -07:00
|
|
|
import { Log, InnerLogger } from '../logger';
|
2020-04-02 17:56:14 -07:00
|
|
|
import * as fs from 'fs';
|
|
|
|
import * as os from 'os';
|
|
|
|
import * as path from 'path';
|
2019-12-12 17:55:54 -08:00
|
|
|
import * as readline from 'readline';
|
2020-04-01 14:42:47 -07:00
|
|
|
import * as removeFolder from 'rimraf';
|
|
|
|
import * as stream from 'stream';
|
|
|
|
import * as util from 'util';
|
2020-01-07 15:27:45 -08:00
|
|
|
import { TimeoutError } from '../errors';
|
2020-04-01 14:42:47 -07:00
|
|
|
import { helper } from '../helper';
|
2019-12-12 17:55:54 -08:00
|
|
|
|
2020-04-01 14:42:47 -07:00
|
|
|
const removeFolderAsync = util.promisify(removeFolder);
|
2020-04-02 17:56:14 -07:00
|
|
|
const mkdtempAsync = util.promisify(fs.mkdtemp);
|
|
|
|
const DOWNLOADS_FOLDER = path.join(os.tmpdir(), 'playwright_downloads-');
|
2019-12-12 17:55:54 -08:00
|
|
|
|
2020-04-20 07:52:26 -07:00
|
|
|
const browserLog: Log = {
|
|
|
|
name: 'browser',
|
|
|
|
};
|
|
|
|
|
|
|
|
const browserStdOutLog: Log = {
|
|
|
|
name: 'browser:out',
|
|
|
|
};
|
|
|
|
|
|
|
|
const browserStdErrLog: Log = {
|
|
|
|
name: 'browser:err',
|
|
|
|
severity: 'warning'
|
|
|
|
};
|
|
|
|
|
|
|
|
|
2019-12-12 17:55:54 -08:00
|
|
|
export type LaunchProcessOptions = {
|
|
|
|
executablePath: string,
|
|
|
|
args: string[],
|
2020-04-23 14:45:57 -07:00
|
|
|
env?: {[key: string]: string | number | boolean | undefined},
|
2019-12-12 17:55:54 -08:00
|
|
|
|
|
|
|
handleSIGINT?: boolean,
|
|
|
|
handleSIGTERM?: boolean,
|
|
|
|
handleSIGHUP?: boolean,
|
|
|
|
pipe?: boolean,
|
|
|
|
tempDir?: string,
|
2020-01-08 13:55:38 -08:00
|
|
|
|
|
|
|
// Note: attemptToGracefullyClose should reject if it does not close the browser.
|
|
|
|
attemptToGracefullyClose: () => Promise<any>,
|
2020-01-28 13:07:53 -08:00
|
|
|
onkill: (exitCode: number | null, signal: string | null) => void,
|
2020-04-20 23:24:53 -07:00
|
|
|
logger: InnerLogger,
|
2019-12-12 17:55:54 -08:00
|
|
|
};
|
|
|
|
|
2020-04-02 17:56:14 -07:00
|
|
|
type LaunchResult = {
|
|
|
|
launchedProcess: childProcess.ChildProcess,
|
|
|
|
gracefullyClose: () => Promise<void>,
|
|
|
|
downloadsPath: string
|
|
|
|
};
|
2020-01-08 13:55:38 -08:00
|
|
|
|
|
|
|
export async function launchProcess(options: LaunchProcessOptions): Promise<LaunchResult> {
|
2020-04-20 07:52:26 -07:00
|
|
|
const logger = options.logger;
|
2020-02-07 11:48:55 -08:00
|
|
|
const stdio: ('ignore' | 'pipe')[] = options.pipe ? ['ignore', 'pipe', 'pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'];
|
2020-04-20 07:52:26 -07:00
|
|
|
logger._log(browserLog, `<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}),
|
2019-12-12 17:55:54 -08:00
|
|
|
stdio
|
|
|
|
}
|
|
|
|
);
|
|
|
|
if (!spawnedProcess.pid) {
|
|
|
|
let reject: (e: Error) => void;
|
2020-01-08 13:55:38 -08:00
|
|
|
const result = new Promise<LaunchResult>((f, r) => reject = r);
|
2019-12-12 17:55:54 -08:00
|
|
|
spawnedProcess.once('error', error => {
|
|
|
|
reject(new Error('Failed to launch browser: ' + error));
|
|
|
|
});
|
|
|
|
return result;
|
|
|
|
}
|
2020-04-20 07:52:26 -07:00
|
|
|
logger._log(browserLog, `<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-04-20 07:52:26 -07:00
|
|
|
logger._log(browserStdOutLog, data);
|
2020-03-23 15:08:02 -07:00
|
|
|
});
|
|
|
|
|
|
|
|
const stderr = readline.createInterface({ input: spawnedProcess.stderr });
|
|
|
|
stderr.on('line', (data: string) => {
|
2020-04-20 07:52:26 -07:00
|
|
|
logger._log(browserStdErrLog, data);
|
2020-03-23 15:08:02 -07:00
|
|
|
});
|
2019-12-12 17:55:54 -08:00
|
|
|
|
2020-04-02 17:56:14 -07:00
|
|
|
const downloadsPath = await mkdtempAsync(DOWNLOADS_FOLDER);
|
|
|
|
|
2019-12-12 17:55:54 -08:00
|
|
|
let processClosed = false;
|
|
|
|
const waitForProcessToClose = new Promise((fulfill, reject) => {
|
2020-01-28 13:07:53 -08:00
|
|
|
spawnedProcess.once('exit', (exitCode, signal) => {
|
2020-04-20 07:52:26 -07:00
|
|
|
logger._log(browserLog, `<process did exit ${exitCode}, ${signal}>`);
|
2019-12-12 17:55:54 -08:00
|
|
|
processClosed = true;
|
2019-12-19 14:51:49 -08:00
|
|
|
helper.removeEventListeners(listeners);
|
2020-01-28 13:07:53 -08:00
|
|
|
options.onkill(exitCode, signal);
|
2019-12-12 17:55:54 -08:00
|
|
|
// Cleanup as processes exit.
|
2020-04-02 17:56:14 -07:00
|
|
|
Promise.all([
|
|
|
|
removeFolderAsync(downloadsPath),
|
|
|
|
options.tempDir ? removeFolderAsync(options.tempDir) : Promise.resolve()
|
|
|
|
]).catch((err: Error) => console.error(err)).then(fulfill);
|
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', () => {
|
|
|
|
gracefullyClose().then(() => process.exit(130));
|
|
|
|
}));
|
|
|
|
}
|
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-01-28 13:07:53 -08:00
|
|
|
let gracefullyClosing = false;
|
2019-12-12 17:55:54 -08:00
|
|
|
async function gracefullyClose(): Promise<void> {
|
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-04-20 07:52:26 -07:00
|
|
|
logger._log(browserLog, `<forecefully close>`);
|
2020-01-28 13:07:53 -08:00
|
|
|
killProcess();
|
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-04-20 07:52:26 -07:00
|
|
|
logger._log(browserLog, `<gracefully close start>`);
|
2020-04-02 16:57:12 -07:00
|
|
|
await options.attemptToGracefullyClose().catch(() => killProcess());
|
2019-12-12 17:55:54 -08:00
|
|
|
await waitForProcessToClose;
|
2020-04-20 07:52:26 -07:00
|
|
|
logger._log(browserLog, `<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-04-20 07:52:26 -07:00
|
|
|
logger._log(browserLog, `<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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Attempt to remove temporary profile directory to avoid littering.
|
|
|
|
try {
|
2020-01-13 13:33:25 -08:00
|
|
|
if (options.tempDir)
|
|
|
|
removeFolder.sync(options.tempDir);
|
2019-12-12 17:55:54 -08:00
|
|
|
} catch (e) { }
|
|
|
|
}
|
2020-01-28 13:07:53 -08:00
|
|
|
|
2020-04-02 17:56:14 -07:00
|
|
|
return { launchedProcess: spawnedProcess, gracefullyClose, downloadsPath };
|
2019-12-12 17:55:54 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
export function waitForLine(process: childProcess.ChildProcess, inputStream: stream.Readable, regex: RegExp, timeout: number, timeoutError: TimeoutError): Promise<RegExpMatchArray> {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const rl = readline.createInterface({ input: inputStream });
|
|
|
|
let stderr = '';
|
|
|
|
const listeners = [
|
|
|
|
helper.addEventListener(rl, 'line', onLine),
|
|
|
|
helper.addEventListener(rl, 'close', () => onClose()),
|
|
|
|
helper.addEventListener(process, 'exit', () => onClose()),
|
|
|
|
helper.addEventListener(process, 'error', error => onClose(error))
|
|
|
|
];
|
|
|
|
const timeoutId = timeout ? setTimeout(onTimeout, timeout) : 0;
|
|
|
|
|
|
|
|
function onClose(error?: Error) {
|
|
|
|
cleanup();
|
|
|
|
reject(new Error([
|
|
|
|
'Failed to launch browser!' + (error ? ' ' + error.message : ''),
|
|
|
|
stderr,
|
|
|
|
'',
|
|
|
|
'TROUBLESHOOTING: https://github.com/Microsoft/playwright/blob/master/docs/troubleshooting.md',
|
|
|
|
'',
|
|
|
|
].join('\n')));
|
|
|
|
}
|
|
|
|
|
|
|
|
function onTimeout() {
|
|
|
|
cleanup();
|
|
|
|
reject(timeoutError);
|
|
|
|
}
|
|
|
|
|
|
|
|
function onLine(line: string) {
|
|
|
|
stderr += line + '\n';
|
|
|
|
const match = line.match(regex);
|
|
|
|
if (!match)
|
|
|
|
return;
|
|
|
|
cleanup();
|
|
|
|
resolve(match);
|
|
|
|
}
|
|
|
|
|
|
|
|
function cleanup() {
|
|
|
|
if (timeoutId)
|
|
|
|
clearTimeout(timeoutId);
|
|
|
|
helper.removeEventListeners(listeners);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|