diff --git a/client/src/components/landing_page.tsx b/client/src/components/landing_page.tsx index d6047b6..ac612dd 100644 --- a/client/src/components/landing_page.tsx +++ b/client/src/components/landing_page.tsx @@ -130,7 +130,7 @@ function LandingPage() { const lines = data.split('\n'); const [header, line2] = lines; if (!(header.replace(' ', '').startsWith("CPU,MEM"))) { - console.warn("unexpected CSV `stats.csv`, expected 'CPU,MEM\\n0.2,0.2\\n', got", header) + console.info("Not displaying server stats: received unexpected: ", header) } if (line2) { let values = line2.split(',') @@ -138,10 +138,9 @@ function LandingPage() { setUsageMem(100 * Number(values[1])); } }).catch(err => { - console.info('stats.csv does not exist.') + console.info('server stats unavailable') + console.debug(err) }) - - }, []) return
diff --git a/relay/index.mjs b/relay/index.mjs index e465e2f..1148c9e 100644 --- a/relay/index.mjs +++ b/relay/index.mjs @@ -9,6 +9,8 @@ import os from 'os'; import fs from 'fs'; import anonymize from 'ip-anonymize'; import { importTrigger, importStatus } from './import.mjs' +import process from'process'; +import { spawn } from 'child_process' // import fs from 'fs' /** @@ -53,8 +55,31 @@ const server = app express.static(path.join(getGameDir(owner,repo),".lake","gamedata"))(req, res, next); }) .use('/data/stats', (req, res, next) => { - // stats file for server usage - express.static(path.join(__dirname, '..', 'games', 'stats.csv'))(req, res, next); + // Returns a CSV of the form + // + // CPU,Mem + // 0.21,0.65 + // + // which contains the current server usage. + + const statsProcess = spawn('/bin/bash', [path.join(__dirname, "stats.sh"), process.pid]) + + let outputData = '' + let errorData = '' + statsProcess.stdout.on('data', (data) => { + outputData += data.toString(); + }) + statsProcess.stderr.on('data', (data) => { + errorData += data.toString(); + }) + statsProcess.on('close', (code) => { + if (code === 0) { + res.send(outputData); + } else { + res.status(500).send(`Error executing script: ${errorData}`) + console.error(`stats.sh exited with code ${code}. Error: ${errorData}`) + } + }) }) .use('/', router) .listen(PORT, () => console.log(`Listening on ${PORT}`)); diff --git a/relay/stats.sh b/relay/stats.sh new file mode 100755 index 0000000..8ad4c8f --- /dev/null +++ b/relay/stats.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +# first argument is the process ID +pid="$1" + +# number of CPUs available +nproc=$(nproc --all) + +# hacky way to print the content of a CSV file containing CPU/Mem usage of the process +top -bn2 -p $pid | awk -v nproc=$nproc 'NR > 16 {$12=substr($0,72); printf "CPU, MEM\n%.2f, %.2f\n", $9/nproc, $10}'