-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathcluster.js
89 lines (54 loc) · 1.59 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
85
86
87
88
89
const cluster = require("cluster");
const os = require("os");
const { config } = require("./helper");
const { master, slave, pool } = require("./handler");
if(cluster.isMaster){
const cpus = config.worker === "auto" ? os.cpus().length : config.worker;
for(let i = 0; i < cpus; i++){
cluster.fork();
}
refresh_pool();
cluster.on("exit", function(worker, code, signal){
if((code !== 0) && !worker.exitedAfterDisconnect){
console.warn("Worker " + worker.id + " crashed. Starting a new worker...");
cluster.fork();
refresh_pool();
}
});
cluster.on("message", master);
process.on("SIGUSR2", function(){
restartWorker();
});
global.worker_pool = pool;
require("./server");
}
else{
require("./handler");
process.on("message", slave);
}
function restartWorker(workerIndex){
workerIndex || (workerIndex = 0);
const workers = Object.values(cluster.workers);
const worker = workers[workerIndex];
if(!worker){
return;
}
worker.on("exit", function(){
if(!worker.exitedAfterDisconnect) {
return;
}
console.info("Exited process: " + worker.process.pid);
cluster.fork().on("listening", function(){
restartWorker(workerIndex + 1);
});
refresh_pool();
});
worker.disconnect();
}
function refresh_pool(){
const workers = Object.values(cluster.workers);
for(let i = 0; i < workers.length; i++){
const worker = workers[i];
pool[worker.id] = worker;
}
}