systemquery/src/lib/core/InfoBroker.mjs

84 lines
2.2 KiB
JavaScript

"use strict";
import path from 'path';
import fs from 'fs';
import sysinfo from 'systeminformation';
import log from '../../lib/io/NamespacedLog.mjs'; const l = log("infobroker");
// HACK: Make sure __dirname is defined when using es6 modules. I forget where I found this - a PR with a source URL would be great :D
const __dirname = import.meta.url.slice(7, import.meta.url.lastIndexOf("/"));
class InfoBroker {
constructor(sysquery) {
this.sysquery = sysquery;
this.allowed_tables = {
// name → sysinfo name
// Note that the order here is the order in the web interface
cpu_live: async () => {
return {
// TODO: Add percentage CPU use here
frequency: await sysinfo.cpuCurrentSpeed(),
temperature: await sysinfo.cpuTemperature()
};
},
cpu: "cpu",
meta: async () => await this.make_table_meta()
};
}
/**
* Determines if the given table name is valid or not.
* @param {string} name The table name to validate.
* @return {Boolean} Whether the table name is valid (true) or not (false).
*/
is_valid_table(name) {
return Object.keys(this.allowed_tables).includes(name);
}
/**
* Returns a list of known table names.
* @return {string[]} A list of known table names.
*/
list_tables() {
return Object.keys(this.allowed_tables);
}
async make_table_meta() {
return {
version: `${this.sysquery.version}-${this.sysquery.commit.substring(0, 7)}`,
versions_env: process.versions,
pid: process.pid,
uptime: process.uptime(),
memory: process.memoryUsage(),
peers_connected: this.sysquery.agent.connected_peers()
.map(peer => { return {
id: peer.id,
name: peer.name
}})
};
}
async fetch_table(name) {
if(!(typeof name === "string"))
throw new Exception(`Error: Expected name to be of type string, but received value of type ${typeof name} instead.`);
if(!this.is_valid_table(name)) {
l.warn(`Unrecognised table '${name}' requested, returning null`);
return null;
}
let name_translated = this.allowed_tables[name];
if(typeof name_translated === "function")
return await name_translated();
return await sysinfo[name_translated]();
}
}
export default InfoBroker;