-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
108 lines (88 loc) · 2.21 KB
/
index.ts
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
103
104
105
106
107
108
import { exec } from "child_process";
import cluster from "cluster";
import { cpus } from "os";
interface options {
instance?: number;
log?: boolean;
}
enum logTypesEnum {
INFO = "info",
ERROR = "error",
}
/**
* Module exports.
* @public
*/
/**
* Module dependencies.
* @private
*/
/**
* @param {number} port port of currently running application
* @param {options} opts options of middleware
*/
export default async function grupo(port: number, opts: options) {
const instances = opts.instance || 0;
const logs = opts.log || false;
if (!logs) {
console.log = function () {};
}
let pid: string;
try {
pid = await getPid(port);
runWorkers(pid, instances);
} catch (err) {
logger(err, logTypesEnum.ERROR);
}
}
/**
* @param {string} pid pid of parent process
* @param {number} instance instance of fork count
*/
async function runWorkers(pid: string, instance: number) {
const totalCPUs = instance || cpus().length;
logger(`Number of CPUs is ${totalCPUs}`, logTypesEnum.INFO);
logger(`Master ${pid} is running`, logTypesEnum.INFO);
for (let i = 0; i < totalCPUs; i++) {
cluster.fork();
}
cluster.on("exit", (worker) => {
logger(`worker ${worker.process.pid} died`, logTypesEnum.INFO);
logger("new worker creating again", logTypesEnum.INFO);
cluster.fork();
});
}
/**
*
* @param {number} port to find pid by port
* @returns {Promise<string>} returns pid of application
*/
async function getPid(port: number): Promise<string> {
return await new Promise((resolve, reject) => {
exec(`lsof -n -i :${port} | grep LISTEN`, (err, stdout) => {
if (err) {
reject(err);
}
let out: string;
// Getting everytime 1st element
out = stdout.match(/\b(\w+)\b/g)[1];
resolve(out);
});
});
}
/**
*
* @param {string} message message of log
* @param {logTypesEnum} type type of log
*/
function logger(message: string, type: logTypesEnum) {
switch (type) {
case logTypesEnum.INFO:
console.log("\x1b[36m%s\x1b[0m", `[${logTypesEnum.INFO}]: ${message}`);
break;
case logTypesEnum.ERROR:
console.log("\x1b[31m%s\x1b[0m", `[${logTypesEnum.INFO}]: ${message}`);
break;
}
}
module.exports = grupo;