Add graceful closure of HTTP connections

When closing down the HTTP and HTTPS servers existing connections are
not closed by Node.js, and may live on forever if they are actively in
use.  A common case where this happens is if Prometheus is set up with a
short interval for collections.

To close down the active connections they need to be tracked and closed
when the server is closed, add the HttpCloser class which encapsulates
the tracking and closure process behind a simple interface and use this
to close down the HTTP and HTTPS server on the master.
This commit is contained in:
Hornwitser committed 2020-12-28 07:05:04 +01:00
1 parent e8405cbf77
commit 16525ae07c
3 files changed
+352 -2

No files matched your search

+7 -2
View File
@@ -49,6 +49,7 @@ let db = {
// homebrew modules
const generateSslCert = require("./src/generate_ssl_cert");
const HttpCloser = require("./src/HttpCloser");
const routes = require("./src/routes");
const libDatabase = require("@clusterio/lib/database");
const libSchema = require("@clusterio/lib/schema");
@@ -72,7 +73,9 @@ const bodyParser = require("body-parser");
const fileUpload = require("express-fileupload");
const app = express();
let httpServer;
let httpServerCloser;
let httpsServer;
let httpsServerCloser;
app.use(cookieParser());
app.use(bodyParser.json({
@@ -496,8 +499,8 @@ async function shutdown() {
let stopTasks = [];
logger.info("Stopping HTTP(S) server");
if (httpServer) { stopTasks.push(new Promise(resolve => httpServer.close(resolve))); }
if (httpsServer) { stopTasks.push(new Promise(resolve => httpsServer.close(resolve))); }
if (httpServer) { stopTasks.push(httpServerCloser.close()); }
if (httpsServer) { stopTasks.push(httpsServerCloser.close()); }
await Promise.all(stopTasks);
logger.info(`Clusterio cleanly exited in ${Date.now() - exitStartTime}ms`);
@@ -1982,6 +1985,7 @@ async function startServer() {
// Only start listening for connections after all plugins have loaded
if (httpPort) {
httpServer = new (require("http").Server)(app);
httpServerCloser = new HttpCloser(httpServer);
await listen(httpServer, httpPort, bindAddress);
logger.info(`Listening for HTTP on port ${httpServer.address().port}`);
}
@@ -2002,6 +2006,7 @@ async function startServer() {
key: privateKey,
cert: certificate,
}, app);
httpsServerCloser = new HttpCloser(httpsServer);
await listen(httpsServer, httpsPort, bindAddress);
logger.info(`Listening for HTTPS on port ${httpsServer.address().port}`);
}