dnc/manager.js

81 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2021-10-23 12:25:28 +02:00
2021-10-23 16:21:40 +02:00
async function exitHandler(options, exitCode) {
shutdown().then(()=>{
setTimeout(function() {
process.exit();
}, 1000);
}).catch(()=>{
setTimeout(function() {
process.exit();
}, 10000);
2021-10-23 12:25:28 +02:00
});
2021-10-23 16:21:40 +02:00
}
[`SIGINT`, `SIGUSR1`, `SIGUSR2`,`SIGTERM`].forEach((eventType) => {
process.on(eventType, exitHandler.bind(null, eventType));
});
2021-10-23 12:25:28 +02:00
2021-10-23 16:21:40 +02:00
var shutdownTasks = []
2021-10-23 12:25:28 +02:00
2021-10-23 16:21:40 +02:00
export const addShutdownTask = function(task,maxDuration=5000){
shutdownTasks.push({t:task,d:maxDuration});
};
2021-10-23 12:25:28 +02:00
2021-10-23 16:21:40 +02:00
export const shutdown = function(){
return new Promise((res,rej)=>{
console.log("Shuting down ...");
2021-10-23 12:25:28 +02:00
2021-10-23 16:21:40 +02:00
var maxDuration = 1000;
var running = 0;
var timeout = null;
2021-10-23 12:25:28 +02:00
2021-10-23 16:21:40 +02:00
function mayShutdown(force=false){
if(running==0||force){
if(timeout!=null)clearInterval(timeout);
res();
2021-10-23 12:25:28 +02:00
}
2021-10-23 16:21:40 +02:00
}
running++;
for (var i = 0; i < shutdownTasks.length; i++) {
try {
if(shutdownTasks[i].d>maxDuration)maxDuration=shutdownTasks[i].d;
running++;
let a = shutdownTasks[i].t();
if(typeof a.then == "function"){
a.then(()=>{
2021-10-23 12:25:28 +02:00
running--;
2021-10-23 16:21:40 +02:00
mayShutdown();
2022-08-26 22:19:58 +02:00
}).catch(()=>{
running--;
mayShutdown();
2021-10-23 16:21:40 +02:00
});
}else{
2021-10-23 12:25:28 +02:00
running--;
2021-10-23 16:21:40 +02:00
if(shutdownTasks.length-1 == i){
mayShutdown();
}
2021-10-23 12:25:28 +02:00
}
2021-10-23 16:21:40 +02:00
} catch (e) {
running--;
mayShutdown();
2021-10-23 12:25:28 +02:00
}
2021-10-23 16:21:40 +02:00
}
running--;
timeout = setTimeout(function () {
timeout = null;
mayShutdown(true);
}, maxDuration);
mayShutdown();
});
};
export const saveShutdown = function(){
shutdown().then(() => {
setTimeout(function() { //some save time
process.exit();
}, 1000);
}).catch(() => {
setTimeout(function() { //shutdown on error with more save time
process.exit();
}, 10000);
});
2021-10-23 12:25:28 +02:00
}