forked from shadowsocks/shadowsocks-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
56 lines (51 loc) · 1.53 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
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');
logger.info(`System 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 () => {
logger.info(`Worker [${ process.pid }] started`);
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) => {
logger.error(`worker [${ worker.process.pid }][${ worker.id }] died`);
for(w in cluster.workers) {
process.env.mainWorker = w;
break;
}
cluster.fork();
});
} else {
startWorker();
}