neutral-link/main.js

91 lines
2.5 KiB
JavaScript
Raw Permalink Normal View History

2023-11-28 19:03:02 +00:00
const http = require('http');
const url = require('url');
const fs = require('fs');
const os = require('os');
const osutils = require('os-utils');
const {statfs} = require('fs');
2023-11-28 19:04:33 +00:00
const { exec } = require('child_process');
2023-11-28 19:03:02 +00:00
const server = http.createServer(async (req, res) => {
const parsedUrl = url.parse(req.url, true);
const query = parsedUrl.query;
if (parsedUrl.pathname === '/metrics' && query.key) {
const config = JSON.parse(fs.readFileSync('config.json'));
if (query.key === config.AUTH_KEY) {
var metrics = await getMetrics()
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(metrics));
} else {
res.statusCode = 401;
res.end('Unauthorized');
}
} else {
res.statusCode = 404;
res.end('Not Found');
}
2023-11-28 19:04:33 +00:00
// Restart the machine
if (parsedUrl.pathname === '/restart' && query.key) {
const config = JSON.parse(fs.readFileSync('config.json'));
if (query.key === config.AUTH_KEY) {
//Restart the machine
exec("sudo reboot", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(metrics));
} else {
res.statusCode = 401;
res.end('Unauthorized');
}
} else {
res.statusCode = 404;
res.end('Not Found');
}
2023-11-28 19:03:02 +00:00
});
server.listen(4000, () => {
console.log('Server is running on port 4000');
});
function getMetrics() {
return new Promise((resolve, reject) => {
const space = statfs("/", (err, stats) => {
if (err) {
throw err
}
var resp = null
osutils.cpuUsage(function(cpuUsage) {
resp = {
cpu: Math.round(cpuUsage * 1000),
usedram: osutils.totalmem() - osutils.freemem(),
totalram: osutils.totalmem(),
usedisk: stats.blocks - stats.bfree,
totaldisk: stats.blocks
}
resolve(resp)
})
})
})
}