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'); const { exec } = require('child_process'); 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'); } // 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'); } }); 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) }) }) }) }