Skip to content
Myr

Improve graceful exit (#714)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ehmicky · committed by GitHub · parent 8ef8e90 · Browse files · 8 files+168 added−122 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+168 added−122 removed

  • tests:+79 added−25 removed
  • other:+89 added−97 removed

8 files+168 added−122 removed

modified:lib/kill.js+18 added-19 removed
modified:lib/stream.js+8 added-9 removed
104 unmodified lines
105 }106};107108// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)109export const getSpawnedResult = async (109export const getSpawnedResult = async ({110 spawned,111 {encoding, buffer, maxBuffer, timeout, killSignal, cleanup, detached},111 options: {encoding, buffer, maxBuffer, timeout, killSignal, cleanup, detached},112 context,113 stdioStreamsGroups,114) => {115 const finalizers = [];116 cleanupOnExit(spawned, cleanup, detached, finalizers);114 controller,115}) => {116 const removeExitHandler = cleanupOnExit(spawned, cleanup, detached);117 const customStreams = getCustomStreams(stdioStreamsGroups);118119 const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, stdioStreams: stdioStreamsGroups[index], encoding, buffer, maxBuffer}));120 const allPromise = getAllPromise({spawned, encoding, buffer, maxBuffer});
7 unmodified lines
128 ...waitForCustomStreamsEnd(customStreams),129 ]),130 ...throwOnCustomStreamsError(customStreams),131 ...throwIfStreamError(spawned.stdin),132 ...throwOnTimeout({spawned, timeout, killSignal, context, finalizers}),132 ...throwOnTimeout({spawned, timeout, killSignal, context, controller}),133 ]);134 } catch (error) {135 spawned.kill();136 const results = await Promise.all([
3 unmodified lines
140 ]);141 cleanupStdioStreams(customStreams, error);142 return results;143 } finally {144 for (const finalizer of finalizers) {145 finalizer();146 }144 controller.abort();145 removeExitHandler?.();146 }147};
modified:test/fixtures/no-killable.js+5 added-3 removed
modified:test/kill.js+74 added-22 removed
8 unmodified lines
9setFixtureDir();1011const TIMEOUT_REGEXP = /timed out after/;1213test('kill("SIGKILL") should terminate cleanly', async t => {14 const subprocess = execa('no-killable.js', {stdio: ['ipc']});13const spawnNoKillable = async (forceKillAfterTimeout, options) => {14 const subprocess = execa('no-killable.js', {15 stdio: ['pipe', 'pipe', 'pipe', 'ipc'],16 forceKillAfterTimeout,17 ...options,18 });19 await pEvent(subprocess, 'message');20 return {subprocess};21};2223test('kill("SIGKILL") should terminate cleanly', async t => {24 const {subprocess} = await spawnNoKillable();2526 subprocess.kill('SIGKILL');2719 const {signal} = await t.throwsAsync(subprocess);28 const {isTerminated, signal} = await t.throwsAsync(subprocess);29 t.true(isTerminated);30 t.is(signal, 'SIGKILL');31});3233// `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).34// Therefore, this feature and those tests do not make sense on Windows.35if (process.platform !== 'win32') {26 test('`forceKillAfterTimeout: false` should not kill after a timeout', async t => {27 const subprocess = execa('no-killable.js', {stdio: ['ipc']});28 await pEvent(subprocess, 'message');36 const testNoForceKill = async (t, forceKillAfterTimeout, killArgument) => {37 const {subprocess} = await spawnNoKillable(forceKillAfterTimeout);3830 subprocess.kill('SIGTERM', {forceKillAfterTimeout: false});39 subprocess.kill(killArgument);4041 await setTimeout(6e3);42 t.true(isRunning(subprocess.pid));43 subprocess.kill('SIGKILL');4435 const {signal} = await t.throwsAsync(subprocess);45 const {isTerminated, signal} = await t.throwsAsync(subprocess);46 t.true(isTerminated);47 t.is(signal, 'SIGKILL');37 });48 };4939 const testForceKill = async (t, killArguments) => {40 const subprocess = execa('no-killable.js', {stdio: ['ipc']});41 await pEvent(subprocess, 'message');50 test('`forceKillAfterTimeout: false` should not kill after a timeout', testNoForceKill, false);51 test('`forceKillAfterTimeout` should not kill after a timeout with other signals', testNoForceKill, true, 'SIGINT');5243 subprocess.kill(...killArguments);53 const testForceKill = async (t, forceKillAfterTimeout, killArgument) => {54 const {subprocess} = await spawnNoKillable(forceKillAfterTimeout);5556 subprocess.kill(killArgument);5745 const {signal} = await t.throwsAsync(subprocess);58 const {isTerminated, signal} = await t.throwsAsync(subprocess);59 t.true(isTerminated);60 t.is(signal, 'SIGKILL');61 };6249 test('`forceKillAfterTimeout: number` should kill after a timeout', testForceKill, ['SIGTERM', {forceKillAfterTimeout: 50}]);50 test('`forceKillAfterTimeout: true` should kill after a timeout', testForceKill, ['SIGTERM', {forceKillAfterTimeout: true}]);51 test('kill("SIGTERM") should kill after a timeout', testForceKill, ['SIGTERM']);52 test('kill() with no arguments should kill after a timeout', testForceKill, []);63 test('`forceKillAfterTimeout: number` should kill after a timeout', testForceKill, 50);64 test('`forceKillAfterTimeout: true` should kill after a timeout', testForceKill, true);65 test('`forceKillAfterTimeout: undefined` should kill after a timeout', testForceKill, undefined);66 test('`forceKillAfterTimeout` should kill after a timeout with the killSignal', testForceKill, 50, 'SIGTERM');6768 const testInvalidForceKill = async (t, forceKillAfterTimeout) => {55 const childProcess = execa('noop.js');69 t.throws(() => {57 childProcess.kill('SIGTERM', {forceKillAfterTimeout});70 execa('empty.js', {forceKillAfterTimeout});71 }, {instanceOf: TypeError, message: /non-negative integer/});59 const {signal} = await t.throwsAsync(childProcess);60 t.is(signal, 'SIGTERM');72 };7374 test('`forceKillAfterTimeout` should not be NaN', testInvalidForceKill, Number.NaN);75 test('`forceKillAfterTimeout` should not be negative', testInvalidForceKill, -1);7677 test('`forceKillAfterTimeout` works with the "signal" option', async t => {78 const abortController = new AbortController();79 const {subprocess} = await spawnNoKillable(1, {signal: abortController.signal});80 abortController.abort();81 const {isTerminated, signal, isCanceled} = await t.throwsAsync(subprocess);82 t.false(isTerminated);83 t.is(signal, undefined);84 t.true(isCanceled);85 });8687 test.serial('`forceKillAfterTimeout` works with the "timeout" option', async t => {88 const {subprocess} = await spawnNoKillable(1, {timeout: 2e3});89 const {isTerminated, signal, timedOut} = await t.throwsAsync(subprocess);90 t.true(isTerminated);91 t.is(signal, 'SIGTERM');92 t.true(timedOut);93 });9495 test('`forceKillAfterTimeout` works with the "maxBuffer" option', async t => {96 const {subprocess} = await spawnNoKillable(1, {maxBuffer: 1});97 const {isTerminated, signal} = await t.throwsAsync(subprocess);98 t.false(isTerminated);99 t.is(signal, undefined);100 });101102 test('`forceKillAfterTimeout` works with "error" events on childProcess', async t => {103 const {subprocess} = await spawnNoKillable(1);104 subprocess.emit('error', new Error('test'));105 const {isTerminated, signal} = await t.throwsAsync(subprocess);106 t.false(isTerminated);107 t.is(signal, undefined);108 });109110 test('`forceKillAfterTimeout` works with "error" events on childProcess.stdout', async t => {111 const {subprocess} = await spawnNoKillable(1);112 subprocess.stdout.destroy(new Error('test'));113 const {isTerminated, signal} = await t.throwsAsync(subprocess);114 t.false(isTerminated);115 t.is(signal, undefined);116 });117}118119test('execa() returns a promise with kill()', async t => {120 const subprocess = execa('noop.js', ['foo']);
187 unmodified lines
modified:index.d.ts+20 added-27 removed
467 unmodified lines
468 */469 readonly killSignal?: string | number;470471 /**472 If the child process is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).473474 The grace period is 5 seconds by default. This feature can be disabled with `false`.475476 This works when the child process is terminated by either:477 - the `signal`, `timeout`, `maxBuffer` or `cleanup` option478 - calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with no arguments479480 This does not work when the child process is terminated by either:481 - calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with an argument482 - calling [`process.kill(subprocess.pid)`](https://nodejs.org/api/process.html#processkillpid-signal)483 - sending a termination signal from another process484485 Also, this does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events): `SIGKILL` and `SIGTERM` both terminate the process immediately. Other packages (such as [`taskkill`](https://github.com/sindresorhus/taskkill)) can be used to achieve fail-safe termination on Windows.486487 @default 5000488 */489 forceKillAfterTimeout?: number | false;490491 /**492 If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.493494 @default false495 */
244 unmodified lines
740741export type ExecaError<OptionsType extends Options = Options> = ExecaCommonReturnValue<false, OptionsType> & ExecaCommonError;742export type ExecaSyncError<OptionsType extends SyncOptions = SyncOptions> = ExecaCommonReturnValue<true, OptionsType> & ExecaCommonError;743724export type KillOptions = {725 /**726 Milliseconds to wait for the child process to terminate before sending `SIGKILL`.727728 Can be disabled with `false`.729730 @default 5000731 */732 forceKillAfterTimeout?: number | false;733};734744type StreamUnlessIgnored<745 StreamIndex extends string,746 OptionsType extends Options = Options,747> = ChildProcessStream<IgnoresStreamResult<StreamIndex, OptionsType>>;
40 unmodified lines
788 onRejected?: (reason: ExecaError<OptionsType>) => ResultType | PromiseLike<ResultType>789 ): Promise<ExecaReturnValue<OptionsType> | ResultType>;790791 /**783 Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal), except if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`. Note that this graceful termination does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events) (`SIGKILL` and `SIGTERM` has the same effect of force-killing the process immediately.) If you want to achieve graceful termination on Windows, you have to use other means, such as [`taskkill`](https://github.com/sindresorhus/taskkill).784 */785 kill(signal?: string, options?: KillOptions): void;786787 /**792 [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process's `stdout` to `target`, which can be:793 - Another `execa()` return value794 - A writable stream795 - A file path string
124 unmodified lines
920 }921 \*\/922}923```920921@example <caption>Graceful termination</caption>922```923const subprocess = execa('node');924925setTimeout(() => {926 subprocess.kill('SIGTERM', {927 forceKillAfterTimeout: 2000928 });929}, 1000);930```924*/925export function execa<OptionsType extends Options = {}>(926 file: string | URL,927 arguments?: readonly string[],
358 unmodified lines
modified:index.js+10 added-5 removed
8 unmodified lines
9import {makeError} from './lib/error.js';10import {handleInputAsync, pipeOutputAsync} from './lib/stdio/async.js';11import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';12import {normalizeStdioNode} from './lib/stdio/normalize.js';13import {spawnedKill, validateTimeout} from './lib/kill.js';13import {spawnedKill, validateTimeout, normalizeForceKillAfterTimeout} from './lib/kill.js';14import {addPipeMethods} from './lib/pipe.js';15import {getSpawnedResult, makeAllStream} from './lib/stream.js';16import {mergePromise} from './lib/promise.js';17import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';
34 unmodified lines
52 const options = addDefaultOptions(initialOptions);53 validateTimeout(options);54 options.shell = normalizeFileUrl(options.shell);55 options.env = getEnv(options);56 options.forceKillAfterTimeout = normalizeForceKillAfterTimeout(options.forceKillAfterTimeout);5758 if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {59 // #11660 args.unshift('/q');
19 unmodified lines
80 all = false,81 windowsHide = true,82 verbose = verboseDefault,83 killSignal = 'SIGTERM',84 forceKillAfterTimeout = true,85 ...options86}) => ({87 ...options,88 maxBuffer,
10 unmodified lines
99 all,100 windowsHide,101 verbose,102 killSignal,103 forceKillAfterTimeout,104});105106const handleOutput = (options, value) => {107 if (value === undefined || value === null) {
34 unmodified lines
142 mergePromise(dummySpawned, errorPromise);143 return dummySpawned;144 }145146 const controller = new AbortController();147148 pipeOutputAsync(spawned, stdioStreamsGroups);149145 spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));150 spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned), options, controller);151 spawned.all = makeAllStream(spawned, options);152153 addPipeMethods(spawned);154150 const promise = handlePromise({spawned, options, stdioStreamsGroups, command, escapedCommand});155 const promise = handlePromise({spawned, options, stdioStreamsGroups, command, escapedCommand, controller});156 mergePromise(spawned, promise);157 return spawned;158}159155const handlePromise = async ({spawned, options, stdioStreamsGroups, command, escapedCommand}) => {160const handlePromise = async ({spawned, options, stdioStreamsGroups, command, escapedCommand, controller}) => {161 const context = {timedOut: false};162163 const [164 [exitCode, signal, error],165 stdioResults,166 allResult,162 ] = await getSpawnedResult(spawned, options, context, stdioStreamsGroups);167 ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, controller});168 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));169 const all = handleOutput(options, allResult);170171 if (error || exitCode !== 0 || signal !== null) {
172 unmodified lines
modified:index.test-d.ts+9 added-4 removed
1185 unmodified lines
1186execa('unicorns', {killSignal: 'SIGTERM'});1187execaSync('unicorns', {killSignal: 'SIGTERM'});1188execa('unicorns', {killSignal: 9});1189execaSync('unicorns', {killSignal: 9});1190execa('unicorns', {forceKillAfterTimeout: false});1191execaSync('unicorns', {forceKillAfterTimeout: false});1192execa('unicorns', {forceKillAfterTimeout: 42});1193execaSync('unicorns', {forceKillAfterTimeout: 42});1194execa('unicorns', {forceKillAfterTimeout: undefined});1195execaSync('unicorns', {forceKillAfterTimeout: undefined});1196expectError(execa('unicorns', {forceKillAfterTimeout: 'true'}));1197expectError(execaSync('unicorns', {forceKillAfterTimeout: 'true'}));1198execa('unicorns', {signal: new AbortController().signal});1199expectError(execaSync('unicorns', {signal: new AbortController().signal}));1200execa('unicorns', {windowsVerbatimArguments: true});1201execaSync('unicorns', {windowsVerbatimArguments: true});
4 unmodified lines
1206/* eslint-enable @typescript-eslint/no-floating-promises */1207execa('unicorns').kill();1208execa('unicorns').kill('SIGKILL');1209execa('unicorns').kill(undefined);1202execa('unicorns').kill('SIGKILL', {});1203execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: false});1204execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: 42});1205execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: undefined});1210expectError(execa('unicorns').kill('SIGKILL', {}));12111212expectError(execa(['unicorns', 'arg']));1213expectType<ExecaChildProcess>(execa('unicorns'));1214expectType<ExecaChildProcess>(execa(fileUrl));
99 unmodified lines
modified:readme.md+24 added-33 removed
48 unmodified lines
49- [Cleans up](#cleanup) child processes when the parent process ends.50- Redirect [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1) from/to files, streams, iterables, strings, `Uint8Array` or [objects](docs/transform.md#object-mode).51- [Transform](docs/transform.md) `stdin`/`stdout`/`stderr` with simple functions.52- Iterate over [each text line](docs/transform.md#binary-data) output by the process.53- [Graceful termination](#optionsforcekillaftertimeout).53- [Fail-safe process termination](#forcekillaftertimeout).54- Get [interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal.55- [Strips the final newline](#stripfinalnewline) from the output so you don't have to do `stdout.trim()`.56- Convenience methods to pipe processes' [input](#input) and [output](#redirect-output-to-a-file).57- Can specify file and arguments [as a single string](#execacommandcommand-options) without a shell.
162 unmodified lines
220 */221}222```223224### Graceful termination225226Using SIGTERM, and after 2 seconds, kill it with SIGKILL.227228```js229const subprocess = execa('node');230231setTimeout(() => {232 subprocess.kill('SIGTERM', {233 forceKillAfterTimeout: 2000234 });235}, 1000);236```237224## API225226### Methods227
80 unmodified lines
308The return value of all [asynchronous methods](#methods) is both:309- a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult).310- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with the following additional methods and properties.311326#### kill(signal?, options?)327328Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal) except: if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.329330Note that this graceful termination does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events) (`SIGKILL` and `SIGTERM` has the same effect of force-killing the process immediately.) If you want to achieve graceful termination on Windows, you have to use other means, such as [`taskkill`](https://github.com/sindresorhus/taskkill).331332##### options.forceKillAfterTimeout333334Type: `number | false`\335Default: `5000`336337Milliseconds to wait for the child process to terminate before sending `SIGKILL`.338339Can be disabled with `false`.340312#### all313314Type: `ReadableStream | undefined`315
122 unmodified lines
438439Type: `boolean`440441Whether the process was terminated using either:471- [`childProcess.kill()`](#killsignal-options).442- `childProcess.kill()`.443- A signal sent by another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).444445#### signal446447Type: `string | undefined`448449The name of the signal (like `SIGFPE`) that terminated the process using either:479- [`childProcess.kill()`](#killsignal-options).450- `childProcess.kill()`.451- A signal sent by another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).452453If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.454
298 unmodified lines
753Default: `SIGTERM`754755Signal value to be used when the spawned process will be killed.756757#### forceKillAfterTimeout758759Type: `number | false`\760Default: `5000`761762If the child process is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).763764The grace period is 5 seconds by default. This feature can be disabled with `false`.765766This works when the child process is terminated by either:767- the [`signal`](#signal-1), [`timeout`](#timeout), [`maxBuffer`](#maxbuffer) or [`cleanup`](#cleanup) option768- calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with no arguments769770This does not work when the child process is terminated by either:771- calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with an argument772- calling [`process.kill(subprocess.pid)`](https://nodejs.org/api/process.html#processkillpid-signal)773- sending a termination signal from another process774775Also, this does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events): `SIGKILL` and `SIGTERM` both terminate the process immediately. Other packages (such as [`taskkill`](https://github.com/sindresorhus/taskkill)) can be used to achieve fail-safe termination on Windows.776777#### signal778779Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)780
70 unmodified lines
851```852853### Retry on error854864Gracefully handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:855Safely handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:856857```js858import pRetry from 'p-retry';859
81 unmodified lines