forked from hashrocket/websocket-shootout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run-cluster.js
56 lines (46 loc) · 1.11 KB
/
run-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
'use strict';
const impl = process.argv[2];
if (!impl) {
console.error('No implementation provided');
process.exit(1);
}
switch (impl) {
case 'ws':
case 'uws':
case 'faye':
break;
default:
console.error(`Implementation: ${impl} not valid`);
process.exit(1);
}
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
const onMessage = function (msg) {
Object.keys(cluster.workers).forEach((id) => {
if (+id !== this.id) {
cluster.workers[id].send(msg);
}
});
};
cluster.on('fork', (worker) => worker.on('message', onMessage));
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
const onExit = () => {
cluster.removeAllListeners('exit');
Object.keys(cluster.workers).forEach((id) => {
cluster.workers[id].kill();
});
};
process
.on('SIGINT', onExit)
.on('SIGTERM', onExit);
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
setTimeout(() => cluster.fork(), 1000);
});
} else {
require(`./${impl}/`);
}