Created
April 29, 2013 21:29
-
-
Save blindsey/5484947 to your computer and use it in GitHub Desktop.
Cluster script for running multiple node processes
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
#!/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