This repository has been archived by the owner on Sep 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcluster.js
64 lines (51 loc) · 1.67 KB
/
cluster.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
'use strict';
var cluster = require('cluster'),
util = require('elefrant-util'),
Q = util.q,
chalk = util.chalk,
datefmt = util.dateformat,
numCPUs = require('os').cpus().length;
cluster.setupMaster({
exec: 'server.js'
});
//Show master info in console
console.log(chalk.green('INFO:'), ' Cluster master created');
console.log(' Pid: %d', process.pid);
console.log(' Time: %s', datefmt(new Date(), 'ddd, dd mmm yyyy hh:MM:ss Z'));
// Function to promises fork
function promiseCluster(condition, body) {
var done = Q.defer();
function loop() {
if (!condition()) return done.resolve();
Q.when(body(), loop, done.reject);
}
Q.nextTick(loop);
return done.promise;
}
// Fork workers
var index = 0;
promiseCluster(function () {
return index < numCPUs;
}, function () {
cluster.fork();
index++;
return Q.delay(1000); // arbitrary async
}).done();
// Event when listening worker
cluster.on('listening', function (worker, address) {
console.log(chalk.green('INFO:') + ' The worker #%s is now connected to %s:%d', worker.id, address.address, address.port);
});
// Event when exit worker
cluster.on('exit', function (worker, code, signal) {
console.log(chalk.red('ERROR:') + ' Worker %d died (%s). restarting...', worker.process.pid, signal || code);
// Auto-restart worker
cluster.fork();
});
// Event when disconnect worker
cluster.on('disconnect', function (worker) {
console.log(chalk.yellow('WARN:') + ' The worker #%s has disconnected', worker.id);
});
// Event when death worker
cluster.on('death', function (worker) {
console.log(chalk.red('ERROR:') + ' The worker #%s is death', worker.id);
});