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: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-16 16:48:45 +00:00
|
|
|
console.log('Checking for remaining child processes before exit...');
|
|
|
|
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 => {
|
2019-05-16 16:48:45 +00:00
|
|
|
console.log(`killing process #${counter}`);
|
|
|
|
childProcessArg.kill('SIGINT');
|
|
|
|
counter++;
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
console.log(`Everything looks clean. Ready to exit!`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-19 20:12:21 +00:00
|
|
|
constructor() {
|
|
|
|
// do app specific cleaning before exiting
|
|
|
|
process.on('exit', async () => {
|
|
|
|
await this.killAll();
|
|
|
|
});
|
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 () => {
|
|
|
|
console.log('Ctrl-C...');
|
|
|
|
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 => {
|
|
|
|
console.log('Ctrl-C...');
|
|
|
|
await this.killAll();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|