-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathcluster.js
85 lines (77 loc) · 5.32 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const cluster = require('cluster');
const os = require('os');
const numServer = 1;
const argv = require('yargs').argv;
if (argv.port == undefined)
{
argv.port = 8000;
portnum = 8000;
}
else
{
portnum = argv.port;
}
if (argv.bonus != undefined)
{
if (isNaN(argv.bonus))
{
bonus = 0;
}
else
{
bonus = parseInt(argv.bonus);
}
}
if (cluster.isMaster)
{
const cpus = os.cpus().length;
var count = 0;
var clientCount = 0;
for (let i = 0; i < numServer; i++)
{
console.log(`Forking for ${cpus} CPUs`);
var worker = cluster.fork();
count = 0;
worker.on('message', function(msg)
{
if (typeof msg.workers != 'undefined')
{
console.log ("CLUSTER: Count is :" + count + " ,got count:" + parseInt(msg.workers) + ",clientCount:" + clientCount);
count = parseInt(count) + parseInt(msg.workers);
clientCount = clientCount + 1;
}
});
}
function eachWorker(callback)
{
for (const id in cluster.workers)
{
callback(cluster.workers[id]);
}
}
const updateWorkers = () => {
eachWorker(worker => {
if (clientCount == numServer)
{
worker.send({'count':count});
}
});
count = 0;
clientCount = 0;
};
updateWorkers();
setInterval(updateWorkers, 10000);
cluster.on('exit', (worker, code, signal) =>
{
if (code !== 0 && !worker.exitedAfterDisconnect)
{
console.log(`Worker ${worker.id} crashed. ` +
'Starting a new worker...');
cluster.fork();
}
});
}
else
{
require("./server");
}