-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
server.js
75 lines (68 loc) · 1.9 KB
/
server.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
const cluster = require('cluster');
if(!process.env.numCPUs) {
process.env.numCPUs = 1;
}
if(process.argv.indexOf('--multiCore') > 1) {
process.env.numCPUs = require('os').cpus().length;
}
require('./init/log');
const log4js = require('log4js');
const logger = log4js.getLogger('system');
if(cluster.isMaster) {
logger.info(`System start[${ process.pid }].`);
} else {
logger.info(`Worker start[${ process.pid }].`);
}
process.on('unhandledRejection', (reason, p) => {
logger.error('Unhandled Rejection at: Promise', p, 'reason:', reason);
});
process.on('uncaughtException', (err) => {
logger.error(`Caught exception:`);
logger.error(err);
});
const startWorker = async () => {
require('./init/utils');
require('./init/moveConfigFile');
require('./init/checkConfig');
require('./init/knex');
const initDb = require('./init/loadModels').init;
const runShadowsocks = require('./init/runShadowsocks').run;
await initDb();
await runShadowsocks();
require('./init/loadServices');
require('./init/loadPlugins');
process.send('Worker start');
};
if(cluster.isMaster) {
process.env.mainWorker = 1;
cluster.fork();
cluster.on('message', (worker, message, handle) => {
if(message === 'Worker start' && Object.keys(cluster.workers).length < (+process.env.numCPUs)) {
cluster.fork();
}
});
cluster.on('exit', (worker, code, signal) => {
if(code === 0) { return; }
logger.error(`worker [${ worker.process.pid }][${ worker.id }] died`);
for(const w in cluster.workers) {
process.env.mainWorker = w;
break;
}
cluster.fork();
});
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.on('line', input => {
if(input === 'rs') {
for(const w in cluster.workers) {
cluster.workers[w].kill();
break;
}
}
});
} else {
startWorker();
}