Skip to content

Instantly share code, notes, and snippets.

@blindsey
Created April 29, 2013 21:29
Show Gist options
  • Save blindsey/5484947 to your computer and use it in GitHub Desktop.
Save blindsey/5484947 to your computer and use it in GitHub Desktop.
Cluster script for running multiple node processes
#!/usr/bin/env node
var cluster = require('cluster');
var WORKERS = require('os').cpus().length;
console.debug = function(msg) {
console.log('%s %s', new Date().toISOString(), msg);
}
if (cluster.isMaster) {
for (var i = 0; i < WORKERS; i++) { cluster.fork(); };
process.on('SIGUSR2', function() {
var workers = Object.keys(cluster.workers);
console.debug('SIGUSR2 with ' + workers.length + ' workers running');
// Bring up a new fleet of workers
for (var i = 0; i < WORKERS; i++) { cluster.fork(); }
workers.forEach(function(id) {
var worker = cluster.workers[id];
if (worker.killing) { return; }
console.debug('Disconnecting worker ' + worker.id);
worker.disconnect();
worker.killing = true;
var timeout = setTimeout(function() {
console.debug('Force killed worker ' + worker.id);
worker.kill();
}, 60000);
worker.on('disconnect', function() {
clearTimeout(timeout);
console.debug('Worker ' + worker.id + ' disconnected');
worker.destroy();
});
});
});
cluster.on('exit', function(worker, code, signal) {
// Suicide is true after kill() or disconnect()
if (!worker.suicide) {
console.debug('Worker ' + worker.id + ' died unexpectedly, forking another');
cluster.fork();
}
});
} else {
var server = require("./index.js");
server.listen(process.env.NODE_PORT || 8080);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment