-
Notifications
You must be signed in to change notification settings - Fork 6
/
master.js
64 lines (56 loc) · 1.39 KB
/
master.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
const cluster = require("cluster");
const { SS_PACK, NODE_ENV } = process.env;
const production = NODE_ENV === "production";
const workers = !SS_PACK && production && require("os").cpus().length;
if (production) {
const stopSignals = [
"SIGHUP",
"SIGINT",
"SIGQUIT",
"SIGILL",
"SIGTRAP",
"SIGABRT",
"SIGBUS",
"SIGFPE",
"SIGUSR1",
"SIGSEGV",
"SIGUSR2",
"SIGTERM",
];
stopSignals.forEach((signal) => {
process.on(signal, () => {
console.log(`Got ${signal}, stopping workers...`);
cluster.disconnect(() => {
console.log("All workers stopped, exiting.");
process.exit(0);
});
});
});
} else {
cluster.on("disconnect", () => {
process.exit(1);
});
}
function messageHandler(msg) {
for (const worker of Object.values(cluster.workers)) {
worker.send(msg);
}
}
const workerIdToPid = [];
function setupWorker(worker, id) {
workerIdToPid[id] = worker.process.pid;
worker.on("message", messageHandler);
worker.send({ id });
}
if (!workers) {
require("./server")(0);
} else {
console.log(`Starting server with ${workers} workers`);
for (let i = 0; i < workers; i++) {
setupWorker(cluster.fork(), i);
}
cluster.on("exit", (worker, code, signal) => {
console.log(`worker exit code: ${code} signal: ${signal}`);
setupWorker(cluster.fork(), workerIdToPid.indexOf(worker.process.pid));
});
}