smartexit/ts/index.ts

68 lines
1.9 KiB
TypeScript
Raw Normal View History

2019-05-16 13:10:22 +00:00
import * as plugins from './smartexit.plugins';
2019-05-16 16:48:45 +00:00
export class SmartExit {
2019-05-19 20:12:21 +00:00
public processesToEnd = new plugins.lik.Objectmap<plugins.childProcess.ChildProcess>();
2019-05-19 20:23:38 +00:00
2019-05-19 20:23:17 +00:00
/**
* adds a process to be exited
* @param childProcessArg
*/
public addProcess(childProcessArg: plugins.childProcess.ChildProcess) {
2019-05-19 20:12:21 +00:00
this.processesToEnd.add(childProcessArg);
2019-05-16 16:48:45 +00:00
}
2019-05-19 20:23:17 +00:00
/**
* removes a process to be exited
*/
public removeProcess(childProcessArg: plugins.childProcess.ChildProcess) {
this.processesToEnd.remove(childProcessArg);
}
2019-05-19 20:12:21 +00:00
public async killAll() {
2019-05-23 15:54:41 +00:00
console.log('SMARTEXIT: Checking for remaining child processes before exit...');
2019-05-16 16:48:45 +00:00
if (this.processesToEnd.getArray().length > 0) {
console.log('found remaining child processes');
let counter = 1;
2019-05-19 20:12:21 +00:00
this.processesToEnd.forEach(async childProcessArg => {
const pid = childProcessArg.pid;
2019-05-23 15:54:41 +00:00
console.log(`SMARTEXIT: killing process #${counter} with pid ${pid}`);
plugins.smartdelay.delayFor(10000).then(() => {
if (childProcessArg.killed) {
return;
}
process.kill(-pid, 'SIGKILL');
});
process.kill(-pid, 'SIGINT');
2019-05-16 16:48:45 +00:00
counter++;
});
} else {
2019-05-23 15:54:41 +00:00
console.log(`SMARTEXIT: Everything looks clean. Ready to exit!`);
2019-05-16 16:48:45 +00:00
}
}
2019-05-19 20:12:21 +00:00
constructor() {
// do app specific cleaning before exiting
2019-05-27 13:16:38 +00:00
process.on('exit', async (code) => {
if (code === 0) {
console.log('SMARTEXIT: Process wants to exit');
await this.killAll();
}
2019-05-19 20:12:21 +00:00
});
2019-05-16 16:48:45 +00:00
2019-05-19 20:12:21 +00:00
// catch ctrl+c event and exit normally
process.on('SIGINT', async () => {
2019-05-27 13:16:38 +00:00
console.log('SMARTEXIT: Ctrl-C... or SIGINT signal received!');
2019-05-19 20:12:21 +00:00
await this.killAll();
});
2019-05-16 16:48:45 +00:00
2019-05-19 20:12:21 +00:00
//catch uncaught exceptions, trace, then exit normally
process.on('uncaughtException', async err => {
2019-05-27 13:16:38 +00:00
console.log('SMARTEXIT: uncaught exception...');
console.log(err);
2019-05-19 20:12:21 +00:00
await this.killAll();
2019-05-27 13:16:38 +00:00
process.exit(1);
2019-05-19 20:12:21 +00:00
});
}
}