76 lines
2.5 KiB
JavaScript
76 lines
2.5 KiB
JavaScript
import axios from "axios";
|
|
import 'dotenv/config';
|
|
|
|
function parseKumaMetrics(metricsString) {
|
|
const lines = metricsString.split("\n").map(line => line.trim()).filter(line => line);
|
|
const result = {};
|
|
let currentHelp = null;
|
|
let currentType = null;
|
|
|
|
for (const line of lines) {
|
|
if (line.startsWith("# HELP")) {
|
|
const [, metricName, description] = line.match(/^# HELP (\S+) (.+)$/) || [];
|
|
if (metricName) {
|
|
currentHelp = description;
|
|
result[metricName] = { help: currentHelp, type: currentType, metrics: [] };
|
|
}
|
|
} else if (line.startsWith("# TYPE")) {
|
|
const [, metricName, type] = line.match(/^# TYPE (\S+) (\S+)$/) || [];
|
|
if (metricName) {
|
|
currentType = type;
|
|
if (!result[metricName]) {
|
|
result[metricName] = { help: currentHelp, type: currentType, metrics: [] };
|
|
} else {
|
|
result[metricName].type = type;
|
|
}
|
|
}
|
|
} else {
|
|
const metricRegex = /^(\w+)(?:\{([^}]*)\})?\s+([\d.e+-]+)$/;
|
|
const match = line.match(metricRegex);
|
|
|
|
if (match) {
|
|
const [, metricName, labels, value] = match;
|
|
const labelObject = {};
|
|
|
|
if (labels) {
|
|
labels.split(",").forEach(pair => {
|
|
const [key, val] = pair.split("=");
|
|
labelObject[key.trim()] = val.trim().replace(/^"|"$/g, '');
|
|
});
|
|
}
|
|
|
|
if (!result[metricName]) {
|
|
result[metricName] = { help: currentHelp, type: currentType, metrics: [] };
|
|
}
|
|
|
|
result[metricName].metrics.push({ labels: labelObject, value: parseFloat(value) });
|
|
}
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
async function fetchAndParsePrometheusData() {
|
|
const URI = process.env.URI
|
|
const PASS = process.env.PASS
|
|
try {
|
|
const response = await axios.get(URI, {
|
|
auth: {
|
|
username: "", // Empty username
|
|
password: PASS
|
|
}
|
|
});
|
|
|
|
const prometheusData = response.data;
|
|
// console.log("Metrics Data:", prometheusData);
|
|
|
|
const jsonData = parseKumaMetrics(prometheusData);
|
|
console.log(JSON.stringify(jsonData, null, 2));
|
|
} catch (error) {
|
|
console.error("Error fetching metrics:", error.message);
|
|
}
|
|
}
|
|
|
|
fetchAndParsePrometheusData();
|