launch.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /**
  2. * @license
  3. * Copyright 2023 Google Inc.
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. import childProcess from 'child_process';
  7. import { accessSync } from 'fs';
  8. import os from 'os';
  9. import readline from 'readline';
  10. import { resolveSystemExecutablePath, } from './browser-data/browser-data.js';
  11. import { Cache } from './Cache.js';
  12. import { debug } from './debug.js';
  13. import { detectBrowserPlatform } from './detectPlatform.js';
  14. const debugLaunch = debug('puppeteer:browsers:launcher');
  15. /**
  16. * @public
  17. */
  18. export function computeExecutablePath(options) {
  19. return new Cache(options.cacheDir).computeExecutablePath(options);
  20. }
  21. /**
  22. * @public
  23. */
  24. export function computeSystemExecutablePath(options) {
  25. options.platform ??= detectBrowserPlatform();
  26. if (!options.platform) {
  27. throw new Error(`Cannot download a binary for the provided platform: ${os.platform()} (${os.arch()})`);
  28. }
  29. const path = resolveSystemExecutablePath(options.browser, options.platform, options.channel);
  30. try {
  31. accessSync(path);
  32. }
  33. catch (error) {
  34. throw new Error(`Could not find Google Chrome executable for channel '${options.channel}' at '${path}'.`);
  35. }
  36. return path;
  37. }
  38. /**
  39. * @public
  40. */
  41. export function launch(opts) {
  42. return new Process(opts);
  43. }
  44. /**
  45. * @public
  46. */
  47. export const CDP_WEBSOCKET_ENDPOINT_REGEX = /^DevTools listening on (ws:\/\/.*)$/;
  48. /**
  49. * @public
  50. */
  51. export const WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX = /^WebDriver BiDi listening on (ws:\/\/.*)$/;
  52. const processListeners = new Map();
  53. const dispatchers = {
  54. exit: (...args) => {
  55. processListeners.get('exit')?.forEach(handler => {
  56. return handler(...args);
  57. });
  58. },
  59. SIGINT: (...args) => {
  60. processListeners.get('SIGINT')?.forEach(handler => {
  61. return handler(...args);
  62. });
  63. },
  64. SIGHUP: (...args) => {
  65. processListeners.get('SIGHUP')?.forEach(handler => {
  66. return handler(...args);
  67. });
  68. },
  69. SIGTERM: (...args) => {
  70. processListeners.get('SIGTERM')?.forEach(handler => {
  71. return handler(...args);
  72. });
  73. },
  74. };
  75. function subscribeToProcessEvent(event, handler) {
  76. const listeners = processListeners.get(event) || [];
  77. if (listeners.length === 0) {
  78. process.on(event, dispatchers[event]);
  79. }
  80. listeners.push(handler);
  81. processListeners.set(event, listeners);
  82. }
  83. function unsubscribeFromProcessEvent(event, handler) {
  84. const listeners = processListeners.get(event) || [];
  85. const existingListenerIdx = listeners.indexOf(handler);
  86. if (existingListenerIdx === -1) {
  87. return;
  88. }
  89. listeners.splice(existingListenerIdx, 1);
  90. processListeners.set(event, listeners);
  91. if (listeners.length === 0) {
  92. process.off(event, dispatchers[event]);
  93. }
  94. }
  95. /**
  96. * @public
  97. */
  98. export class Process {
  99. #executablePath;
  100. #args;
  101. #browserProcess;
  102. #exited = false;
  103. // The browser process can be closed externally or from the driver process. We
  104. // need to invoke the hooks only once though but we don't know how many times
  105. // we will be invoked.
  106. #hooksRan = false;
  107. #onExitHook = async () => { };
  108. #browserProcessExiting;
  109. constructor(opts) {
  110. this.#executablePath = opts.executablePath;
  111. this.#args = opts.args ?? [];
  112. opts.pipe ??= false;
  113. opts.dumpio ??= false;
  114. opts.handleSIGINT ??= true;
  115. opts.handleSIGTERM ??= true;
  116. opts.handleSIGHUP ??= true;
  117. // On non-windows platforms, `detached: true` makes child process a
  118. // leader of a new process group, making it possible to kill child
  119. // process tree with `.kill(-pid)` command. @see
  120. // https://nodejs.org/api/child_process.html#child_process_options_detached
  121. opts.detached ??= process.platform !== 'win32';
  122. const stdio = this.#configureStdio({
  123. pipe: opts.pipe,
  124. dumpio: opts.dumpio,
  125. });
  126. const env = opts.env || {};
  127. debugLaunch(`Launching ${this.#executablePath} ${this.#args.join(' ')}`, {
  128. detached: opts.detached,
  129. env: Object.keys(env).reduce((res, key) => {
  130. if (key.toLowerCase().startsWith('puppeteer_')) {
  131. res[key] = env[key];
  132. }
  133. return res;
  134. }, {}),
  135. stdio,
  136. });
  137. this.#browserProcess = childProcess.spawn(this.#executablePath, this.#args, {
  138. detached: opts.detached,
  139. env,
  140. stdio,
  141. });
  142. debugLaunch(`Launched ${this.#browserProcess.pid}`);
  143. if (opts.dumpio) {
  144. this.#browserProcess.stderr?.pipe(process.stderr);
  145. this.#browserProcess.stdout?.pipe(process.stdout);
  146. }
  147. subscribeToProcessEvent('exit', this.#onDriverProcessExit);
  148. if (opts.handleSIGINT) {
  149. subscribeToProcessEvent('SIGINT', this.#onDriverProcessSignal);
  150. }
  151. if (opts.handleSIGTERM) {
  152. subscribeToProcessEvent('SIGTERM', this.#onDriverProcessSignal);
  153. }
  154. if (opts.handleSIGHUP) {
  155. subscribeToProcessEvent('SIGHUP', this.#onDriverProcessSignal);
  156. }
  157. if (opts.onExit) {
  158. this.#onExitHook = opts.onExit;
  159. }
  160. this.#browserProcessExiting = new Promise((resolve, reject) => {
  161. this.#browserProcess.once('exit', async () => {
  162. debugLaunch(`Browser process ${this.#browserProcess.pid} onExit`);
  163. this.#clearListeners();
  164. this.#exited = true;
  165. try {
  166. await this.#runHooks();
  167. }
  168. catch (err) {
  169. reject(err);
  170. return;
  171. }
  172. resolve();
  173. });
  174. });
  175. }
  176. async #runHooks() {
  177. if (this.#hooksRan) {
  178. return;
  179. }
  180. this.#hooksRan = true;
  181. await this.#onExitHook();
  182. }
  183. get nodeProcess() {
  184. return this.#browserProcess;
  185. }
  186. #configureStdio(opts) {
  187. if (opts.pipe) {
  188. if (opts.dumpio) {
  189. return ['ignore', 'pipe', 'pipe', 'pipe', 'pipe'];
  190. }
  191. else {
  192. return ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'];
  193. }
  194. }
  195. else {
  196. if (opts.dumpio) {
  197. return ['pipe', 'pipe', 'pipe'];
  198. }
  199. else {
  200. return ['pipe', 'ignore', 'pipe'];
  201. }
  202. }
  203. }
  204. #clearListeners() {
  205. unsubscribeFromProcessEvent('exit', this.#onDriverProcessExit);
  206. unsubscribeFromProcessEvent('SIGINT', this.#onDriverProcessSignal);
  207. unsubscribeFromProcessEvent('SIGTERM', this.#onDriverProcessSignal);
  208. unsubscribeFromProcessEvent('SIGHUP', this.#onDriverProcessSignal);
  209. }
  210. #onDriverProcessExit = (_code) => {
  211. this.kill();
  212. };
  213. #onDriverProcessSignal = (signal) => {
  214. switch (signal) {
  215. case 'SIGINT':
  216. this.kill();
  217. process.exit(130);
  218. case 'SIGTERM':
  219. case 'SIGHUP':
  220. void this.close();
  221. break;
  222. }
  223. };
  224. async close() {
  225. await this.#runHooks();
  226. if (!this.#exited) {
  227. this.kill();
  228. }
  229. return await this.#browserProcessExiting;
  230. }
  231. hasClosed() {
  232. return this.#browserProcessExiting;
  233. }
  234. kill() {
  235. debugLaunch(`Trying to kill ${this.#browserProcess.pid}`);
  236. // If the process failed to launch (for example if the browser executable path
  237. // is invalid), then the process does not get a pid assigned. A call to
  238. // `proc.kill` would error, as the `pid` to-be-killed can not be found.
  239. if (this.#browserProcess &&
  240. this.#browserProcess.pid &&
  241. pidExists(this.#browserProcess.pid)) {
  242. try {
  243. debugLaunch(`Browser process ${this.#browserProcess.pid} exists`);
  244. if (process.platform === 'win32') {
  245. try {
  246. childProcess.execSync(`taskkill /pid ${this.#browserProcess.pid} /T /F`);
  247. }
  248. catch (error) {
  249. debugLaunch(`Killing ${this.#browserProcess.pid} using taskkill failed`, error);
  250. // taskkill can fail to kill the process e.g. due to missing permissions.
  251. // Let's kill the process via Node API. This delays killing of all child
  252. // processes of `this.proc` until the main Node.js process dies.
  253. this.#browserProcess.kill();
  254. }
  255. }
  256. else {
  257. // on linux the process group can be killed with the group id prefixed with
  258. // a minus sign. The process group id is the group leader's pid.
  259. const processGroupId = -this.#browserProcess.pid;
  260. try {
  261. process.kill(processGroupId, 'SIGKILL');
  262. }
  263. catch (error) {
  264. debugLaunch(`Killing ${this.#browserProcess.pid} using process.kill failed`, error);
  265. // Killing the process group can fail due e.g. to missing permissions.
  266. // Let's kill the process via Node API. This delays killing of all child
  267. // processes of `this.proc` until the main Node.js process dies.
  268. this.#browserProcess.kill('SIGKILL');
  269. }
  270. }
  271. }
  272. catch (error) {
  273. throw new Error(`${PROCESS_ERROR_EXPLANATION}\nError cause: ${isErrorLike(error) ? error.stack : error}`);
  274. }
  275. }
  276. this.#clearListeners();
  277. }
  278. waitForLineOutput(regex, timeout = 0) {
  279. if (!this.#browserProcess.stderr) {
  280. throw new Error('`browserProcess` does not have stderr.');
  281. }
  282. const rl = readline.createInterface(this.#browserProcess.stderr);
  283. let stderr = '';
  284. return new Promise((resolve, reject) => {
  285. rl.on('line', onLine);
  286. rl.on('close', onClose);
  287. this.#browserProcess.on('exit', onClose);
  288. this.#browserProcess.on('error', onClose);
  289. const timeoutId = timeout > 0 ? setTimeout(onTimeout, timeout) : undefined;
  290. const cleanup = () => {
  291. if (timeoutId) {
  292. clearTimeout(timeoutId);
  293. }
  294. rl.off('line', onLine);
  295. rl.off('close', onClose);
  296. this.#browserProcess.off('exit', onClose);
  297. this.#browserProcess.off('error', onClose);
  298. };
  299. function onClose(error) {
  300. cleanup();
  301. reject(new Error([
  302. `Failed to launch the browser process!${error ? ' ' + error.message : ''}`,
  303. stderr,
  304. '',
  305. 'TROUBLESHOOTING: https://pptr.dev/troubleshooting',
  306. '',
  307. ].join('\n')));
  308. }
  309. function onTimeout() {
  310. cleanup();
  311. reject(new TimeoutError(`Timed out after ${timeout} ms while waiting for the WS endpoint URL to appear in stdout!`));
  312. }
  313. function onLine(line) {
  314. stderr += line + '\n';
  315. const match = line.match(regex);
  316. if (!match) {
  317. return;
  318. }
  319. cleanup();
  320. // The RegExp matches, so this will obviously exist.
  321. resolve(match[1]);
  322. }
  323. });
  324. }
  325. }
  326. const PROCESS_ERROR_EXPLANATION = `Puppeteer was unable to kill the process which ran the browser binary.
  327. This means that, on future Puppeteer launches, Puppeteer might not be able to launch the browser.
  328. Please check your open processes and ensure that the browser processes that Puppeteer launched have been killed.
  329. If you think this is a bug, please report it on the Puppeteer issue tracker.`;
  330. /**
  331. * @internal
  332. */
  333. function pidExists(pid) {
  334. try {
  335. return process.kill(pid, 0);
  336. }
  337. catch (error) {
  338. if (isErrnoException(error)) {
  339. if (error.code && error.code === 'ESRCH') {
  340. return false;
  341. }
  342. }
  343. throw error;
  344. }
  345. }
  346. /**
  347. * @internal
  348. */
  349. export function isErrorLike(obj) {
  350. return (typeof obj === 'object' && obj !== null && 'name' in obj && 'message' in obj);
  351. }
  352. /**
  353. * @internal
  354. */
  355. export function isErrnoException(obj) {
  356. return (isErrorLike(obj) &&
  357. ('errno' in obj || 'code' in obj || 'path' in obj || 'syscall' in obj));
  358. }
  359. /**
  360. * @public
  361. */
  362. export class TimeoutError extends Error {
  363. /**
  364. * @internal
  365. */
  366. constructor(message) {
  367. super(message);
  368. this.name = this.constructor.name;
  369. Error.captureStackTrace(this, this.constructor);
  370. }
  371. }
  372. //# sourceMappingURL=launch.js.map