Created
November 27, 2014 13:55
-
-
Save greenboxal/02d5e78bd5ec3178c5e2 to your computer and use it in GitHub Desktop.
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 http = require('http'); | |
var WORKER_COUNT = 4; | |
var LISTEN_PORT = 8080; | |
if (cluster.isMaster) { | |
var crashes = [], disconnects = []; | |
var spawnWorker = function(i) { | |
var worker = cluster.fork(); | |
worker.process.once('exit', function(exitCode, signalCode) { | |
console.log('MASTER: Worker #%s(%s) exited: %s %s', i, worker.id, exitCode, signalCode); | |
crashes.push({ | |
index: i, | |
worker: worker.id, | |
suicide: worker.suicide, | |
exitCode: exitCode, | |
signalCode: signalCode, | |
connected: worker.process.connected | |
}); | |
spawnWorker(i); | |
}); | |
worker.process.once('disconnect', function() { | |
console.log('MASTER: Worker #%s(%s) disconnected.', i, worker.id); | |
disconnects.push({ | |
index: i, | |
worker: worker.id, | |
suicide: worker.suicide | |
}); | |
spawnWorker(i); | |
}); | |
worker.once('online', function() { | |
console.log('MASTER: Worker #%s(%s) online.', i, worker.id); | |
}); | |
console.log('MASTER: Spawning worker #%s(%s).', i, worker.id); | |
}; | |
for (var i = 0; i < WORKER_COUNT; i++) { | |
spawnWorker(i); | |
} | |
process.on('SIGINT', function() { | |
console.log('%s crashes, %s disconnects.', crashes.length, disconnects.length); | |
console.dir(crashes); | |
console.dir(disconnects); | |
process.exit(0); | |
}); | |
} else { | |
var crashmaster = null; | |
var server = http.createServer(function(req, res) { | |
if (Math.random() < 0.3) { | |
console.log('WORKER %s: Crashing on next.', cluster.worker.id); | |
process.nextTick(function() { | |
crashmaster.crashMe(lol); | |
}); | |
} else { | |
res.writeHead(200); | |
res.end('OK.'); | |
} | |
}); | |
server.listen(LISTEN_PORT, function() { | |
console.log('WORKER %s: Listening.', cluster.worker.id); | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment