Skip to content

Commit

Permalink
fix: keyError when Prometheuse metric name is normalized
Browse files Browse the repository at this point in the history
prom_metric_name was only changed for _create_prometheus_metric and
not _add_prometheus_sample.
  • Loading branch information
kpetremann committed Jun 25, 2023
1 parent ed110bb commit 97d54b5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
23 changes: 13 additions & 10 deletions mqtt_exporter/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,18 +86,16 @@ def _create_prometheus_metric(prom_metric_name):
if settings.MQTT_EXPOSE_CLIENT_ID:
labels.append("client_id")

prom_metric_name = _normalize_prometheus_metric_name(prom_metric_name)

try:
prom_metrics[prom_metric_name] = Gauge(
prom_metric_name, "metric generated from MQTT message.", labels
)
LOG.info("creating prometheus metric: %s", prom_metric_name)
except ValueError as error:
LOG.error("unable to create prometheus metric '%s': %s", prom_metric_name, error)
prom_metrics[prom_metric_name] = Gauge(
prom_metric_name, "metric generated from MQTT message.", labels
)
LOG.info("creating prometheus metric: %s", prom_metric_name)


def _add_prometheus_sample(topic, prom_metric_name, metric_value, client_id):
if prom_metric_name not in prom_metrics:
return

labels = {settings.TOPIC_LABEL: topic}
if settings.MQTT_EXPOSE_CLIENT_ID:
labels["client_id"] = client_id
Expand Down Expand Up @@ -165,7 +163,12 @@ def _parse_metrics(data, topic, client_id, prefix=""):
.replace("/", "_")
)
prom_metric_name = re.sub(r"\((.*?)\)", "", prom_metric_name)
_create_prometheus_metric(prom_metric_name)
prom_metric_name = _normalize_prometheus_metric_name(prom_metric_name)
try:
_create_prometheus_metric(prom_metric_name)
except ValueError as error:
LOG.error("unable to create prometheus metric '%s': %s", prom_metric_name, error)
return

# expose the sample to prometheus
_add_prometheus_sample(topic, prom_metric_name, metric_value, client_id)
Expand Down
4 changes: 2 additions & 2 deletions tests/functional/test_expose_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ def _exec(client_id, mocker):
userdata = {"client_id": client_id}
msg = mocker.Mock()
msg.topic = "zigbee2mqtt/garage"
msg.payload = '{"temperature": "23.5", "humidity": "40.5"}'
msg.payload = '{"temperature°C": "23.5", "humidity": "40.5"}'
main.expose_metrics(None, userdata, msg)

temperatures = main.prom_metrics["mqtt_temperature"].collect()
temperatures = main.prom_metrics["mqtt_temperatureC"].collect()
humidity = main.prom_metrics["mqtt_humidity"].collect()

return temperatures, humidity
Expand Down

0 comments on commit 97d54b5

Please sign in to comment.