Created
January 26, 2015 18:57
-
-
Save dahjelle/e2a1f5c28dab4f9a348c to your computer and use it in GitHub Desktop.
Attempting cluster-based graceful restarts in Hapi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Hapi = require('hapi'); | |
var PORT = process.env.PORT || 3000; | |
var server = new Hapi.Server(); | |
server.connection({ | |
port: PORT | |
}); | |
server.route({ | |
method: 'GET', | |
path: '/{path*}', | |
handler: { | |
directory: { | |
path: './public', | |
listing: false, | |
index: true | |
} | |
} | |
}); | |
// based off of http://stackoverflow.com/a/10997753/185651 | |
var cluster = function(server) { | |
var cluster = require('cluster'); | |
var numCPUs = require('os').cpus().length; | |
var workerList = new Array(); | |
var sigkill = false; | |
if (cluster.isMaster) { | |
for (var i = 0; i < numCPUs; i++) { | |
var env = process.env; | |
var worker = cluster.fork(env); | |
workerList.push(worker); | |
} | |
process.on('SIGUSR2',function(){ | |
console.log("Received SIGUSR2 from system"); | |
console.log("There are " + workerList.length + " workers running"); | |
workerList.forEach(function(worker){ | |
console.log("Sending STOP message to worker PID=" + worker.pid); | |
worker.send({cmd: "stop"}); | |
}); | |
for (var i = 0; i < numCPUs; i++) { | |
var env = process.env; | |
var worker = cluster.fork(env); | |
workerList.push(worker); | |
} | |
}); | |
process.on('SIGINT',function(){ | |
sigint = true; | |
process.exit(); | |
}); | |
cluster.on('exit', function(worker) { | |
if (sigkill) { | |
logger.warn("SIGKINT received - not respawning workers"); | |
return; | |
} | |
var newWorker = cluster.fork(); | |
console.log('Worker ' + worker.pid + ' died and it will be re-spawned'); | |
removeWorkerFromListByPID(worker.pid); | |
workerList.push(newWorker); | |
}); | |
} else { | |
process.on('message', function(msg) { | |
if (msg.cmd && msg.cmd == 'stop') { | |
console.log("Received STOP signal from master"); | |
server.stop({ | |
timeout: 50000 | |
}, function() { | |
console.log('hapi done'); | |
process.exit(); | |
}); | |
} | |
}); | |
server.start(function() { | |
console.log("server started"); | |
}); | |
} | |
function removeWorkerFromListByPID(pid) { | |
var counter = -1; | |
workerList.forEach(function(worker){ | |
++counter; | |
if (worker.pid === pid) { | |
workerList.splice(counter, 1); | |
} | |
}); | |
} | |
}; | |
cluster( server ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment