uptime-kuma-metrics/index.js
2025-02-08 10:27:27 +07:00

93 lines
2.9 KiB
JavaScript

import axios from "axios";
import 'dotenv/config';
import express from 'express';
const app = express();
const PORT = process.env.PORT;
app.get('/metrics', async (req, res) => {
try {
const metrics = await fetchAndParsePrometheusData();
res.json(metrics);
} catch (error) {
res.status(500).json({ error: 'Server error', details: error.message });
}
})
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
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));
return jsonData;
} catch (error) {
console.error("Error fetching metrics:", error.message);
}
}