-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
102 lines (86 loc) · 2.28 KB
/
index.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
'use strict';
var cluster = require('cluster');
module.exports = function (workerRun) {
var port = parseInt(process.env.PORT) || 8085;
var numCPUs = parseInt(process.env.CLUSTER_WORKERS_COUNT, 10) || 1;
if (numCPUs > 1 && cluster.isMaster) {
new WorkerPool(port, numCPUs);
} else {
workerRun();
}
}
function portscanner(firstPort, count, done){
var portNext = firstPort;
var ports = [];
var getPort = function (cb) {
var net = require('net');
var port = portNext;
portNext += 1;
var server = net.createServer();
server.listen(port, function (err) {
server.once('close', function () {
cb(port);
});
server.close();
});
server.on('error', function (err) {
getPort(cb);
});
}
var next = function(port){
ports.push(port);
if (ports.length >= count) {
done(ports);
} else {
getPort(next);
}
};
getPort(next);
}
function WorkerPool(firstPort, size) {
var self = this;
self._workers = [];
self._workersMap = {};
self._index = 0;
portscanner(firstPort, size, function(ports){
var size = ports.length;
for (var i = 0; i < size; i++) {
var port = ports[i];
self._createWorker(port);
}
});
cluster.on('exit', function (worker, code, signal) {
console.log('worker ' + worker.id + ' died');
self._restartWorker(worker.id);
});
}
WorkerPool.prototype._createWorker = function(port) {
var self = this;
var index = ++self._index;
var new_worker_env = {};
new_worker_env["WORKER_NAME"] = "worker" + index;
new_worker_env["PORT"] = port;
var info = cluster.fork(new_worker_env);
var worker = {
env: new_worker_env,
port: port,
index: index,
pid: info.process.pid,
id: info.id
}
self._workers.push(worker);
self._workersMap[worker.id] = worker;
}
WorkerPool.prototype._restartWorker = function(workerId) {
var self = this;
var workerInfo = self._workersMap[workerId];
if (!workerInfo) {
return ;
}
if (cluster.workers[workerId]) {
cluster.workers[workerId].destroy();
}
try { process.kill(workerInfo.pid); } catch(ex) {}
var port = workerInfo.port;
self._createWorker(port)
};