-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(bin): adds exits hook to manage child processes termination
- Loading branch information
Showing
1 changed file
with
38 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.' | ||
); | ||
}); | ||
} |