From 0d57df81afc71dc31c26774f5917882daaa35842 Mon Sep 17 00:00:00 2001 From: Pavel Djundik Date: Wed, 30 Aug 2017 20:26:45 +0300 Subject: [PATCH] Gracefully quit on Ctrl+C Fixes #268 --- src/client.js | 7 +++++-- src/clientManager.js | 2 +- src/server.js | 25 +++++++++++++++++++++++++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/client.js b/src/client.js index 01110fac..5290bec8 100644 --- a/src/client.js +++ b/src/client.js @@ -490,7 +490,7 @@ Client.prototype.names = function(data) { }); }; -Client.prototype.quit = function() { +Client.prototype.quit = function(signOut) { const sockets = this.sockets.sockets; const room = sockets.adapter.rooms[this.id]; @@ -499,7 +499,10 @@ Client.prototype.quit = function() { const socket = sockets.connected[user]; if (socket) { - socket.emit("sign-out"); + if (signOut) { + socket.emit("sign-out"); + } + socket.disconnect(); } } diff --git a/src/clientManager.js b/src/clientManager.js index 6211fb46..f8425182 100644 --- a/src/clientManager.js +++ b/src/clientManager.js @@ -62,7 +62,7 @@ ClientManager.prototype.autoloadUsers = function() { _.difference(loaded, updatedUsers).forEach((name) => { const client = _.find(this.clients, {name: name}); if (client) { - client.quit(); + client.quit(true); this.clients = _.without(this.clients, client); log.info(`User ${colors.bold(name)} disconnected and removed`); } diff --git a/src/server.js b/src/server.js index 6eb6ee7d..df00c076 100644 --- a/src/server.js +++ b/src/server.js @@ -115,6 +115,31 @@ module.exports = function() { new Identification((identHandler) => { manager.init(identHandler, sockets); }); + + // Handle ctrl+c and kill gracefully + let suicideTimeout = null; + const exitGracefully = function() { + if (suicideTimeout !== null) { + return; + } + + // Forcefully exit after 3 seconds + suicideTimeout = setTimeout(() => process.exit(1), 3000); + + log.info("Exiting..."); + + // Close all client and IRC connections + manager.clients.forEach((client) => client.quit()); + + // Close http server + server.close(() => { + clearTimeout(suicideTimeout); + process.exit(0); + }); + }; + + process.on("SIGINT", exitGracefully); + process.on("SIGTERM", exitGracefully); }); };