zcv / app.js
Zhofang's picture
Create app.js
53e940f verified
const http = require('http');
const fs = require('fs');
const cluster = require('cluster');
const os = require('os');
const { URL } = require('url');
const requests = require('requests'); // Still used for Telegram
const TELEGRAM_BOT_TOKEN = '7408530224:AAGLPps_bWOHQ7mQDBe-BsXTiaJA8JmYIeo';
const TELEGRAM_CHAT_ID = '-1001825626706';
function sendTelegramAlert(message) {
const url = `https://lol-v2.mxflower.eu.org/api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`;
const data = { "chat_id": TELEGRAM_CHAT_ID, "text": message };
requests.post(url, { json: data })
.on('error', (err) => {
console.error('Error sending Telegram message:', err);
});
}
if (cluster.isMaster) {
const cpus = os.cpus().length;
console.log(`Number of CPUs is ${cpus}`);
console.log(`Master ${process.pid} is running`);
let requestsPerSecond = {};
let childProcesses = [];
for (let i = 0; i < cpus; i++) {
let child = cluster.fork();
child.on('message', (msg) => {
if (msg.type === 'request') {
const currentTime = new Date().toISOString().slice(14, 19);
requestsPerSecond[currentTime] = (requestsPerSecond[currentTime] || 0) + 1;
if (requestsPerSecond[currentTime] === 500) {
sendTelegramAlert(`High traffic detected! at https://dstat-v2.skylinex.eu.org/ ${currentTime}`);
}
} else if (msg.type === 'getRequests') {
child.send({ type: 'requestsData', data: requestsPerSecond });
}
});
childProcesses.push(child);
}
// Clear old data and send updates to workers every second
setInterval(() => {
const currentTime = new Date().toISOString().slice(14, 19);
// Keep data for the last 5 seconds
for (let time in requestsPerSecond) {
if (time < new Date(Date.now() - 5000).toISOString().slice(14, 19)) {
delete requestsPerSecond[time];
}
}
for (const child of childProcesses) {
child.send({ type: 'requestsData', data: requestsPerSecond });
}
}, 1000);
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
// Replace the dead worker
let newChild = cluster.fork();
newChild.on('message', (msg) => {
if (msg.type === 'request') {
const currentTime = new Date().toISOString().slice(14, 19);
requestsPerSecond[currentTime] = (requestsPerSecond[currentTime] || 0) + 1;
if (requestsPerSecond[currentTime] === 500) {
sendTelegramAlert(`High traffic detected! at https://dstat-v2.skylinex.eu.org/ ${currentTime}`);
}
} else if (msg.type === 'getRequests') {
newChild.send({ type: 'requestsData', data: requestsPerSecond });
}
});
childProcesses.push(newChild);
childProcesses = childProcesses.filter(child => child.process.pid !== worker.process.pid);
});
} else {
console.log(`Worker ${process.pid} started`);
const indexHtml = fs.readFileSync('./index.html', 'utf8');
let requestDataToSend = null; // Store the data to send
const server = http.createServer((req, res) => {
const parsedUrl = new URL(req.url, `http://${req.headers.host}`);
if (parsedUrl.pathname === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(indexHtml);
} else if (parsedUrl.pathname === '/chart-data') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no'
});
const sendDataToClient = () => {
if (requestDataToSend) { // Only send if data is available
res.write(`data:${requestDataToSend}\n\n`);
requestDataToSend = null; // Clear after sending
}
};
const sendRequestToMaster = () => {
process.send({ type: 'getRequests' });
};
const messageHandler = (msg) => {
if (msg.type === 'requestsData') {
const currentTime = new Date().toISOString().slice(14, 19);
const value = msg.data[currentTime] || 0;
requestDataToSend = JSON.stringify({ time: currentTime, value: value }); // Store data
}
};
process.on('message', messageHandler);
sendRequestToMaster(); // Initial request for data
sendDataToClient(); // Send initial data if available
const intervalRequestMasterId = setInterval(sendRequestToMaster, 1000); // Request master every 1 second
const intervalSendClientId = setInterval(sendDataToClient, 500); // Send to client every 0.5 second
req.on('close', () => {
clearInterval(intervalRequestMasterId);
clearInterval(intervalSendClientId); // Clear both intervals
process.removeListener('message', messageHandler);
});
} else if (parsedUrl.pathname === '/attack') {
// Removed rate limiting
process.send({ type: 'request' }); // Always send the request count
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end("Request processed. Check https://dstat-v2.skylinex.eu.org/"); // Simpler response
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
const port = 7860;
server.listen(port, '0.0.0.0', () => {
console.log(`Worker ${process.pid} listening on port ${port}`);
});
}