Created
May 13, 2012 17:41
-
-
Save rla/2689424 to your computer and use it in GitHub Desktop.
Node.JS cluster startup
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 cluster = require('cluster'); | |
var fs = require('fs'); | |
var config = require('./config.json'); | |
var assets = require('./lib/assets'); | |
// Fork child processes. | |
if (cluster.isMaster) { | |
// Run asset cleanup. | |
assets.cleanupSync(); | |
// And when in production mode, compile them | |
// into a single file. | |
if (process.env.NODE_ENV === 'production') { | |
assets.compileSync(); | |
} | |
// Pidfile contains master process PID. | |
// This is also used by stop.sh. | |
var pidfile = 'master.pid' | |
// Map of workers (PID -> worker). | |
var workers = {}; | |
// Set master process title (shows in `ps`). | |
process.title = config.server.masterTitle; | |
for (var i = 0; i < config.server.processes; i++) { | |
var worker = cluster.fork(); | |
workers[worker.pid] = worker; | |
} | |
// Emitted on death of a worker. | |
cluster.on('death', function(worker) { | |
console.log('Worker ' + worker.pid + ' died.'); | |
// Remove dead worker. | |
delete workers[worker.pid]; | |
// Restart on worker death. | |
worker = cluster.fork(); | |
workers[worker.pid] = worker; | |
}); | |
// Attach signal handler to kill workers | |
// when master is terminated. | |
function cleanup() { | |
console.log('Master stopping.'); | |
for (var pid in workers) { | |
workers[pid].kill(); | |
} | |
// Remove pidfile. | |
fs.unlinkSync(pidfile); | |
process.exit(0); | |
} | |
// Master can be terminated by either SIGTERM | |
// or SIGINT. The latter is used by CTRL+C on console. | |
process.on('SIGTERM', cleanup); | |
process.on('SIGINT', cleanup); | |
// Write pidfile. | |
fs.writeFileSync(pidfile, process.pid); | |
} else { | |
// Set worker process title (shows in `ps`). | |
process.title = config.server.workerTitle; | |
// Set up the server. | |
var server = require('./server').init(); | |
// Workers are terminated by SIGTERM sent | |
// by the master. | |
// http://www.oesmith.co.uk/post/15532216845 | |
process.on('SIGTERM', function () { | |
console.log('Stopping worker ' + process.pid); | |
// Allow requests finish. | |
server.close(); | |
}); | |
// When requests are finished, stop the server. | |
server.on('close', function () { | |
console.log('Worker ' + process.pid + ' stopped'); | |
process.exit(0); | |
}); | |
console.log('Worker ' + process.pid + ' started.'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment