Browse Source

gracefully shut down on SIGTERM

this will close the server, i.e. all new connections will be dropped
while existing connections are able to complete within 30 seconds
otherwise they are dropped and the server force quits
jomo 9 years ago
parent
commit
79da225b9f
1 changed files with 19 additions and 4 deletions
  1. 19 4
      lib/server.js

+ 19 - 4
lib/server.js

@@ -131,18 +131,33 @@ var exp = {};
 exp.boot = function(callback) {
 exp.boot = function(callback) {
   var port = process.env.PORT || 3000;
   var port = process.env.PORT || 3000;
   var bind_ip = process.env.BIND || "0.0.0.0";
   var bind_ip = process.env.BIND || "0.0.0.0";
-  logging.log("Server running on http://" + bind_ip + ":" + port + "/");
   server = http.createServer(requestHandler).listen(port, bind_ip, function() {
   server = http.createServer(requestHandler).listen(port, bind_ip, function() {
+    logging.log("Server running on http://" + bind_ip + ":" + port + "/");
     if (callback) {
     if (callback) {
       callback();
       callback();
     }
     }
   });
   });
+
+  // stop accepting new connections,
+  // wait for established connections to finish (30s max),
+  // then exit
+  process.on("SIGTERM", function() {
+    logging.warn("Got SIGTERM, no longer accepting connections!");
+
+    setTimeout(function() {
+      logging.error("Dropping connections after 30s. Force quit.");
+      process.exit(1);
+    }, 30000);
+
+    server.close(function() {
+      // all connections have been closed
+      process.exit();
+    });
+  });
 };
 };
 
 
 exp.close = function(callback) {
 exp.close = function(callback) {
-  server.close(function() {
-    callback();
-  });
+  server.close(callback);
 };
 };
 
 
 module.exports = exp;
 module.exports = exp;