-
Notifications
You must be signed in to change notification settings - Fork 245
/
Copy pathindex.js
89 lines (68 loc) · 2.31 KB
/
index.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 { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');
const moment = require('moment-timezone');
const MEMORY_LIMIT = 250; // MB
const RESTART_DELAY = 3000; // ms
const TIMEZONE = "Africa/Nairobi";
function getLogFileName() {
return `${moment().tz(TIMEZONE).format('YYYY-MM-DD')}.log`;
}
function createTmpFolder() {
const folderName = "tmp";
const folderPath = path.join(__dirname, folderName);
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath);
}
}
createTmpFolder();
function logMessage(message) {
const timestamp = moment().tz(TIMEZONE).format('HH:mm z');
console.log(`[CYPHER-X] ${message}`);
fs.appendFileSync(path.join(__dirname, 'tmp', getLogFileName()), `[${timestamp}] ${message}\n`);
}
function start() {
process.env.SERVER_MEMORY = '716';
process.env.NODE_OPTIONS = '--no-deprecation';
const args = [path.join(__dirname, 'core.js'), ...process.argv.slice(2)];
logMessage('Starting...');
const logFilePath = path.join(__dirname, 'tmp', getLogFileName());
const errorLogStream = fs.createWriteStream(logFilePath, { flags: 'a' });
let p = spawn(process.argv[0], args, {
stdio: ['inherit', 'inherit', 'pipe', 'ipc'],
});
p.stderr.on('data', (data) => {
const errorMsg = `[${moment().tz(TIMEZONE).format('HH:mm z')}] ${data.toString()}`;
console.error(errorMsg);
errorLogStream.write(errorMsg);
});
const memoryCheckInterval = setInterval(() => {
try {
if (!p.pid) return;
const { execSync } = require('child_process');
const memoryUsage = parseFloat(execSync(`ps -o rss= -p ${p.pid}`).toString().trim()) / 1024;
if (memoryUsage > MEMORY_LIMIT) {
logMessage(`Memory usage exceeded ${MEMORY_LIMIT}MB. Restarting...`);
p.kill();
}
} catch (error) {
logMessage(`Memory check failed: ${error.message}`);
}
}, 600000);
p.on('exit', (code) => {
clearInterval(memoryCheckInterval);
logMessage(`Exited with code: ${code}`);
if (code !== 0) {
setTimeout(start, RESTART_DELAY);
}
});
const handleShutdown = (signal) => {
logMessage(`Shutting down CypherX due to ${signal}...`);
p.kill();
errorLogStream.end();
process.exit(0);
};
process.on('SIGINT', handleShutdown);
process.on('SIGTERM', handleShutdown);
}
start();