launch.js 12 KB

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