47 lines
1.4 KiB
Plaintext
47 lines
1.4 KiB
Plaintext
var cluster = require('cluster');
|
|
var fs = require('fs');
|
|
|
|
if (cluster.isMaster) {
|
|
fs.writeFile('./tmp/cluster.pid', process.pid.toString(), function (err) {
|
|
if (err) {
|
|
console.log('Error: unable to create cluster.pid');
|
|
process.exit(1);
|
|
} else {
|
|
console.log('Starting cluster with pid: ' + process.pid);
|
|
//ensure workers exit cleanly
|
|
process.on('SIGINT', function() {
|
|
console.log('Cluster shutting down..');
|
|
setTimeout(function() {
|
|
for (var id in cluster.workers) {
|
|
console.log('Worker shutting down (' + id + ')');
|
|
cluster.workers[id].kill();
|
|
}
|
|
setTimeout(function() {
|
|
// exit the master process
|
|
process.exit(0);
|
|
}, 3000);
|
|
}, 1000);
|
|
});
|
|
|
|
// Count the machine's CPUs
|
|
var cpuCount = require('os').cpus().length;
|
|
|
|
// Create a worker for each CPU
|
|
for (var i = 0; i < cpuCount; i += 1) {
|
|
cluster.fork();
|
|
}
|
|
|
|
// Listen for dying workers
|
|
cluster.on('exit', function (worker, code, signal) {
|
|
if (worker['process']['exitCode'] === 0) {
|
|
console.log('Worker shut down.');
|
|
} else if ((signal != 'SIGINT') && (worker['process']['exitCode'] !== 0) && (worker.exitedAfterDisconnect !== true)) {
|
|
console.log('Cluster restarting...');
|
|
cluster.fork();
|
|
}
|
|
});
|
|
}
|
|
});
|
|
} else {
|
|
require('./instance');
|
|
} |