Skip to content

Commit

Permalink
feat(bin): adds exits hook to manage child processes termination
Browse files Browse the repository at this point in the history
  • Loading branch information
rafamel committed May 6, 2019
1 parent 2506264 commit 85b4ef8
Showing 1 changed file with 38 additions and 9 deletions.
47 changes: 38 additions & 9 deletions src/bin/attach.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,49 @@
import core from '~/core';
import { attach as _attach, options, resolver } from 'exits';
import { attach as _attach, options, resolver, add } from 'exits';
import manager from '~/utils/ps-manager';
import logger from '~/utils/logger';
import { wait } from 'promist';

export default function attach(): void {
_attach();
options({
spawned: {
signals: 'none',
wait: 'all',
sigterm: 0,
sigkill: 5000
},
async resolver(type, arg) {
const silent = await core.get('silent').catch(() => false);

if (silent) return resolver('exit', 0);
return type === 'signal' ? resolver('exit', 1) : resolver(type, arg);
if (silent) {
logger.debug('Silent: exiting with code 0');
return resolver('exit', 0);
}
if (type === 'signal') {
logger.debug('Received a termination signal: exiting with code 1');
return resolver('exit', 1);
}
logger.debug(`Received a ${type} event: `, arg);
return resolver(type, arg);
}
});
add(async () => {
if (manager.isDone()) return;
logger.debug('Sending SIGTERM to all children processes');

let start = Date.now();
manager.kill('SIGTERM');
while (!manager.isDone() && Date.now() - start < 2500) {
await Promise.race([manager.promise(), wait(Date.now() - start)]);
}

if (manager.isDone()) return;
logger.debug('Seding SIGKILL to all children processes');

start = Date.now();
manager.kill('SIGKILL');
while (!manager.isDone() && Date.now() - start < 2500) {
await Promise.race([manager.promise(), wait(Date.now() - start)]);
}

if (manager.isDone()) return;
logger.debug(
'Children processes have timed out without terminating. Exiting main process.'
);
});
}

0 comments on commit 85b4ef8

Please sign in to comment.