Remove unsupported characters in prometheus metrics.

This commit is contained in:
Rick van Drongelen 2025-06-04 16:17:18 +02:00
parent 4a5fe2145c
commit e61ba524d7
No known key found for this signature in database

View file

@ -41,10 +41,10 @@ class Prometheus {
* @param {Array<{name:string,value:?string}>} tags Tags to add to the monitor * @param {Array<{name:string,value:?string}>} tags Tags to add to the monitor
*/ */
constructor(monitor, tags) { constructor(monitor, tags) {
let filteredValidAsciiTags = this.filterValidAsciiTags(tags); let sanitizedTags = this.sanitizeTags(tags);
if (filteredValidAsciiTags.length <= 0) { if (sanitizedTags.length <= 0) {
filteredValidAsciiTags = "null"; sanitizedTags = "null";
} }
this.monitorLabelValues = { this.monitorLabelValues = {
@ -53,27 +53,27 @@ class Prometheus {
monitor_url: monitor.url, monitor_url: monitor.url,
monitor_hostname: monitor.hostname, monitor_hostname: monitor.hostname,
monitor_port: monitor.port, monitor_port: monitor.port,
monitor_tags: filteredValidAsciiTags monitor_tags: sanitizedTags
}; };
} }
/** /**
* Filter tags to remove the ones that contain non-ASCII characters * Sanitize tags to ensure they can be processed by Prometheus.
* See https://github.com/louislam/uptime-kuma/pull/4704#issuecomment-2366524692 * See https://github.com/louislam/uptime-kuma/pull/4704#issuecomment-2366524692
* @param {Array<{name: string, value:?string}>} tags The tags to filter * @param {Array<{name: string, value:?string}>} tags The tags to sanitize
* @returns {string[]} The filtered tags * @returns {string[]} The sanitized tags
*/ */
filterValidAsciiTags(tags) { sanitizeTags(tags) {
const asciiRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/; return tags.reduce((sanitizedTags, tag) => {
return tags.reduce((filteredTags, tag) => { let tagText = tag.name;
if (asciiRegex.test(tag.name)) { tagText = tagText.replace(/[^a-zA-Z0-9_]/g, "")
if (tag.value !== "" && asciiRegex.test(tag.value)) { tagText = tagText.replace(/^[^a-zA-Z_]+/, "")
filteredTags.push(`${tag.name}:${tag.value}`);
} else { if (tagText !== "") {
filteredTags.push(tag.name); sanitizedTags.push(tagText);
}
} }
return filteredTags;
return sanitizedTags;
}, []); }, []);
} }