Improve prometheus metric name sanitization (#126967)

This commit is contained in:
Russell Cloran 2024-10-25 09:33:16 -07:00 committed by GitHub
parent 1a3940575e
commit 3ac3673326
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -89,6 +89,7 @@ CONF_OVERRIDE_METRIC = "override_metric"
COMPONENT_CONFIG_SCHEMA_ENTRY = vol.Schema( COMPONENT_CONFIG_SCHEMA_ENTRY = vol.Schema(
{vol.Optional(CONF_OVERRIDE_METRIC): cv.string} {vol.Optional(CONF_OVERRIDE_METRIC): cv.string}
) )
ALLOWED_METRIC_CHARS = set(string.ascii_letters + string.digits + "_:")
DEFAULT_NAMESPACE = "homeassistant" DEFAULT_NAMESPACE = "homeassistant"
@ -325,12 +326,7 @@ class PrometheusMetrics:
@staticmethod @staticmethod
def _sanitize_metric_name(metric: str) -> str: def _sanitize_metric_name(metric: str) -> str:
return "".join( return "".join(
[ [c if c in ALLOWED_METRIC_CHARS else f"u{hex(ord(c))}" for c in metric]
c
if c in string.ascii_letters + string.digits + "_:"
else f"u{hex(ord(c))}"
for c in metric
]
) )
@staticmethod @staticmethod