smartexit/ts/index.ts

73 lines
2.0 KiB
TypeScript
Raw Normal View History

2019-05-16 13:10:22 +00:00
import * as plugins from './smartexit.plugins';
2019-05-28 07:31:10 +00:00
import { ora } from './smartexit.logging';
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-28 07:31:10 +00:00
ora.text('Checking for remaining child processes before exit...');
2019-05-16 16:48:45 +00:00
if (this.processesToEnd.getArray().length > 0) {
2019-05-28 07:31:10 +00:00
ora.text('found remaining child processes');
2019-05-16 16:48:45 +00:00
let counter = 1;
2019-05-19 20:12:21 +00:00
this.processesToEnd.forEach(async childProcessArg => {
const pid = childProcessArg.pid;
2019-05-28 07:31:10 +00:00
ora.text(`killing process #${counter} with pid ${pid}`);
plugins.smartdelay.delayFor(10000).then(() => {
if (childProcessArg.killed) {
return;
}
2019-05-28 08:28:56 +00:00
process.kill(pid, 'SIGKILL');
});
2019-05-28 08:28:56 +00:00
process.kill(pid, 'SIGINT');
2019-05-16 16:48:45 +00:00
counter++;
});
} else {
2019-05-28 07:31:10 +00:00
ora.text(`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) {
2019-05-28 07:31:10 +00:00
ora.text('Process wants to exit');
2019-05-27 13:16:38 +00:00
await this.killAll();
2019-05-28 08:18:10 +00:00
ora.finishSuccess('Exited ok!');
} else {
ora.finishFail('Exited NOT OK!');
2019-05-27 13:16:38 +00:00
}
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-28 07:31:10 +00:00
ora.text('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-28 07:31:10 +00:00
ora.text('SMARTEXIT: uncaught exception...');
2019-05-27 13:16:38 +00:00
console.log(err);
2019-05-19 20:12:21 +00:00
await this.killAll();
2019-05-28 08:28:56 +00:00
process.exit(1);
2019-05-19 20:12:21 +00:00
});
}
}