const { LogType } = require("loguix") const fs = require("fs") const path = require("path") var CryptoJS = require("crypto-js") const { __glob } = require("./global-variables") const { captureRejectionSymbol } = require("events") const clog = new LogType("Metrics") if(!fs.existsSync(__glob.DATA + path.sep + "metrics.json")) { fs.writeFileSync(__glob.DATA + path.sep + "metrics.json", JSON.stringify([], null, 2)) } module.exports.getDataMetrics = function() { return JSON.parse(fs.readFileSync(__glob.DATA + path.sep + "metrics.json")) } module.exports.getMetrics = function() { const metrics = this.getDataMetrics() var metricsToReturn = new Array() return new Promise(async (resolve, reject) => { // Count the number processed var processed = 0 if(metrics.length == 0) { resolve(metricsToReturn) } await metrics.forEach(async (metric) => { // Try to connect to the metric server with the key in query params named "privatekey" // If the connection is successful, we add the metric to the list of metrics to return const url = `http://${metric.address}:${metric.port}/metrics?privatekey=${metric.key}` const fet = await fetch(url, { method: "GET", headers: { "Accept": "application/json", }, credentials: "include" }).then(res => res.json()) .then(res => { if(res) { metric.data = res metricsToReturn.push(metric) processed++ } else { metric.data = "ERROR" metricsToReturn.push(metric) } if(processed == metrics.length) { resolve(metricsToReturn) } }).catch((err) => { metric.data = "ERROR" metricsToReturn.push(metric) processed++ if(processed == metrics.length) { resolve(metricsToReturn) } }) }) }) } module.exports.addMetric = function(settings) { const metrics = this.getDataMetrics() const metric = { id: makeid(8), name: settings.name, address: settings.address, port: settings.port, key: settings.key, } metrics.push(metric) fs.writeFileSync(__glob.DATA + path.sep + "metrics.json", JSON.stringify(metrics, null, 2)) return "OK" } module.exports.deleteMetric = function(id) { const metrics = this.getDataMetrics() metrics.forEach((metric) => { if(metric.id == id) { metrics.splice(metrics.indexOf(metric), 1) } }) fs.writeFileSync(__glob.DATA + path.sep + "metrics.json", JSON.stringify(metrics, null, 2)) return "OK" } function makeid(length) { var result = []; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; var charactersLength = characters.length; for ( var i = 0; i < length; i++ ) { result.push(characters.charAt(Math.floor(Math.random() * charactersLength))); } return result.join(''); }