Use prometheus_client module directly (#107918)

This commit is contained in:
Marc Mueller 2024-01-14 02:56:22 +01:00 committed by GitHub
parent 2584de6324
commit 3c1e2e17a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -95,9 +95,7 @@ CONFIG_SCHEMA = vol.Schema(
def setup(hass: HomeAssistant, config: ConfigType) -> bool: def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Activate Prometheus component.""" """Activate Prometheus component."""
hass.http.register_view( hass.http.register_view(PrometheusView(config[DOMAIN][CONF_REQUIRES_AUTH]))
PrometheusView(prometheus_client, config[DOMAIN][CONF_REQUIRES_AUTH])
)
conf = config[DOMAIN] conf = config[DOMAIN]
entity_filter = conf[CONF_FILTER] entity_filter = conf[CONF_FILTER]
@ -112,7 +110,6 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
) )
metrics = PrometheusMetrics( metrics = PrometheusMetrics(
prometheus_client,
entity_filter, entity_filter,
namespace, namespace,
climate_units, climate_units,
@ -138,7 +135,6 @@ class PrometheusMetrics:
def __init__( def __init__(
self, self,
prometheus_cli,
entity_filter, entity_filter,
namespace, namespace,
climate_units, climate_units,
@ -147,7 +143,6 @@ class PrometheusMetrics:
default_metric, default_metric,
): ):
"""Initialize Prometheus Metrics.""" """Initialize Prometheus Metrics."""
self.prometheus_cli = prometheus_cli
self._component_config = component_config self._component_config = component_config
self._override_metric = override_metric self._override_metric = override_metric
self._default_metric = default_metric self._default_metric = default_metric
@ -199,20 +194,20 @@ class PrometheusMetrics:
labels = self._labels(state) labels = self._labels(state)
state_change = self._metric( state_change = self._metric(
"state_change", self.prometheus_cli.Counter, "The number of state changes" "state_change", prometheus_client.Counter, "The number of state changes"
) )
state_change.labels(**labels).inc() state_change.labels(**labels).inc()
entity_available = self._metric( entity_available = self._metric(
"entity_available", "entity_available",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"Entity is available (not in the unavailable or unknown state)", "Entity is available (not in the unavailable or unknown state)",
) )
entity_available.labels(**labels).set(float(state.state not in ignored_states)) entity_available.labels(**labels).set(float(state.state not in ignored_states))
last_updated_time_seconds = self._metric( last_updated_time_seconds = self._metric(
"last_updated_time_seconds", "last_updated_time_seconds",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"The last_updated timestamp", "The last_updated timestamp",
) )
last_updated_time_seconds.labels(**labels).set(state.last_updated.timestamp()) last_updated_time_seconds.labels(**labels).set(state.last_updated.timestamp())
@ -259,7 +254,7 @@ class PrometheusMetrics:
for key, value in state.attributes.items(): for key, value in state.attributes.items():
metric = self._metric( metric = self._metric(
f"{state.domain}_attr_{key.lower()}", f"{state.domain}_attr_{key.lower()}",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
f"{key} attribute of {state.domain} entity", f"{key} attribute of {state.domain} entity",
) )
@ -284,7 +279,7 @@ class PrometheusMetrics:
full_metric_name, full_metric_name,
documentation, documentation,
labels, labels,
registry=self.prometheus_cli.REGISTRY, registry=prometheus_client.REGISTRY,
) )
return self._metrics[metric] return self._metrics[metric]
@ -327,7 +322,7 @@ class PrometheusMetrics:
if (battery_level := state.attributes.get(ATTR_BATTERY_LEVEL)) is not None: if (battery_level := state.attributes.get(ATTR_BATTERY_LEVEL)) is not None:
metric = self._metric( metric = self._metric(
"battery_level_percent", "battery_level_percent",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"Battery level as a percentage of its capacity", "Battery level as a percentage of its capacity",
) )
try: try:
@ -339,7 +334,7 @@ class PrometheusMetrics:
def _handle_binary_sensor(self, state): def _handle_binary_sensor(self, state):
metric = self._metric( metric = self._metric(
"binary_sensor_state", "binary_sensor_state",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"State of the binary sensor (0/1)", "State of the binary sensor (0/1)",
) )
value = self.state_as_number(state) value = self.state_as_number(state)
@ -348,7 +343,7 @@ class PrometheusMetrics:
def _handle_input_boolean(self, state): def _handle_input_boolean(self, state):
metric = self._metric( metric = self._metric(
"input_boolean_state", "input_boolean_state",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"State of the input boolean (0/1)", "State of the input boolean (0/1)",
) )
value = self.state_as_number(state) value = self.state_as_number(state)
@ -358,13 +353,13 @@ class PrometheusMetrics:
if unit := self._unit_string(state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)): if unit := self._unit_string(state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)):
metric = self._metric( metric = self._metric(
f"{domain}_state_{unit}", f"{domain}_state_{unit}",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
f"State of the {title} measured in {unit}", f"State of the {title} measured in {unit}",
) )
else: else:
metric = self._metric( metric = self._metric(
f"{domain}_state", f"{domain}_state",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
f"State of the {title}", f"State of the {title}",
) )
@ -388,7 +383,7 @@ class PrometheusMetrics:
def _handle_device_tracker(self, state): def _handle_device_tracker(self, state):
metric = self._metric( metric = self._metric(
"device_tracker_state", "device_tracker_state",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"State of the device tracker (0/1)", "State of the device tracker (0/1)",
) )
value = self.state_as_number(state) value = self.state_as_number(state)
@ -396,7 +391,7 @@ class PrometheusMetrics:
def _handle_person(self, state): def _handle_person(self, state):
metric = self._metric( metric = self._metric(
"person_state", self.prometheus_cli.Gauge, "State of the person (0/1)" "person_state", prometheus_client.Gauge, "State of the person (0/1)"
) )
value = self.state_as_number(state) value = self.state_as_number(state)
metric.labels(**self._labels(state)).set(value) metric.labels(**self._labels(state)).set(value)
@ -404,7 +399,7 @@ class PrometheusMetrics:
def _handle_cover(self, state): def _handle_cover(self, state):
metric = self._metric( metric = self._metric(
"cover_state", "cover_state",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"State of the cover (0/1)", "State of the cover (0/1)",
["state"], ["state"],
) )
@ -419,7 +414,7 @@ class PrometheusMetrics:
if position is not None: if position is not None:
position_metric = self._metric( position_metric = self._metric(
"cover_position", "cover_position",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"Position of the cover (0-100)", "Position of the cover (0-100)",
) )
position_metric.labels(**self._labels(state)).set(float(position)) position_metric.labels(**self._labels(state)).set(float(position))
@ -428,7 +423,7 @@ class PrometheusMetrics:
if tilt_position is not None: if tilt_position is not None:
tilt_position_metric = self._metric( tilt_position_metric = self._metric(
"cover_tilt_position", "cover_tilt_position",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"Tilt Position of the cover (0-100)", "Tilt Position of the cover (0-100)",
) )
tilt_position_metric.labels(**self._labels(state)).set(float(tilt_position)) tilt_position_metric.labels(**self._labels(state)).set(float(tilt_position))
@ -436,7 +431,7 @@ class PrometheusMetrics:
def _handle_light(self, state): def _handle_light(self, state):
metric = self._metric( metric = self._metric(
"light_brightness_percent", "light_brightness_percent",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"Light brightness percentage (0..100)", "Light brightness percentage (0..100)",
) )
@ -453,7 +448,7 @@ class PrometheusMetrics:
def _handle_lock(self, state): def _handle_lock(self, state):
metric = self._metric( metric = self._metric(
"lock_state", self.prometheus_cli.Gauge, "State of the lock (0/1)" "lock_state", prometheus_client.Gauge, "State of the lock (0/1)"
) )
value = self.state_as_number(state) value = self.state_as_number(state)
metric.labels(**self._labels(state)).set(value) metric.labels(**self._labels(state)).set(value)
@ -466,7 +461,7 @@ class PrometheusMetrics:
) )
metric = self._metric( metric = self._metric(
metric_name, metric_name,
self.prometheus_cli.Gauge, prometheus_client.Gauge,
metric_description, metric_description,
) )
metric.labels(**self._labels(state)).set(temp) metric.labels(**self._labels(state)).set(temp)
@ -500,7 +495,7 @@ class PrometheusMetrics:
if current_action := state.attributes.get(ATTR_HVAC_ACTION): if current_action := state.attributes.get(ATTR_HVAC_ACTION):
metric = self._metric( metric = self._metric(
"climate_action", "climate_action",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"HVAC action", "HVAC action",
["action"], ["action"],
) )
@ -514,7 +509,7 @@ class PrometheusMetrics:
if current_mode and available_modes: if current_mode and available_modes:
metric = self._metric( metric = self._metric(
"climate_mode", "climate_mode",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"HVAC mode", "HVAC mode",
["mode"], ["mode"],
) )
@ -528,14 +523,14 @@ class PrometheusMetrics:
if humidifier_target_humidity_percent: if humidifier_target_humidity_percent:
metric = self._metric( metric = self._metric(
"humidifier_target_humidity_percent", "humidifier_target_humidity_percent",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"Target Relative Humidity", "Target Relative Humidity",
) )
metric.labels(**self._labels(state)).set(humidifier_target_humidity_percent) metric.labels(**self._labels(state)).set(humidifier_target_humidity_percent)
metric = self._metric( metric = self._metric(
"humidifier_state", "humidifier_state",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"State of the humidifier (0/1)", "State of the humidifier (0/1)",
) )
try: try:
@ -549,7 +544,7 @@ class PrometheusMetrics:
if current_mode and available_modes: if current_mode and available_modes:
metric = self._metric( metric = self._metric(
"humidifier_mode", "humidifier_mode",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"Humidifier Mode", "Humidifier Mode",
["mode"], ["mode"],
) )
@ -571,7 +566,7 @@ class PrometheusMetrics:
if unit: if unit:
documentation = f"Sensor data measured in {unit}" documentation = f"Sensor data measured in {unit}"
_metric = self._metric(metric, self.prometheus_cli.Gauge, documentation) _metric = self._metric(metric, prometheus_client.Gauge, documentation)
try: try:
value = self.state_as_number(state) value = self.state_as_number(state)
@ -647,7 +642,7 @@ class PrometheusMetrics:
def _handle_switch(self, state): def _handle_switch(self, state):
metric = self._metric( metric = self._metric(
"switch_state", self.prometheus_cli.Gauge, "State of the switch (0/1)" "switch_state", prometheus_client.Gauge, "State of the switch (0/1)"
) )
try: try:
@ -664,7 +659,7 @@ class PrometheusMetrics:
def _handle_automation(self, state): def _handle_automation(self, state):
metric = self._metric( metric = self._metric(
"automation_triggered_count", "automation_triggered_count",
self.prometheus_cli.Counter, prometheus_client.Counter,
"Count of times an automation has been triggered", "Count of times an automation has been triggered",
) )
@ -673,7 +668,7 @@ class PrometheusMetrics:
def _handle_counter(self, state): def _handle_counter(self, state):
metric = self._metric( metric = self._metric(
"counter_value", "counter_value",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"Value of counter entities", "Value of counter entities",
) )
@ -682,7 +677,7 @@ class PrometheusMetrics:
def _handle_update(self, state): def _handle_update(self, state):
metric = self._metric( metric = self._metric(
"update_state", "update_state",
self.prometheus_cli.Gauge, prometheus_client.Gauge,
"Update state, indicating if an update is available (0/1)", "Update state, indicating if an update is available (0/1)",
) )
value = self.state_as_number(state) value = self.state_as_number(state)
@ -695,16 +690,15 @@ class PrometheusView(HomeAssistantView):
url = API_ENDPOINT url = API_ENDPOINT
name = "api:prometheus" name = "api:prometheus"
def __init__(self, prometheus_cli, requires_auth: bool) -> None: def __init__(self, requires_auth: bool) -> None:
"""Initialize Prometheus view.""" """Initialize Prometheus view."""
self.requires_auth = requires_auth self.requires_auth = requires_auth
self.prometheus_cli = prometheus_cli
async def get(self, request): async def get(self, request):
"""Handle request for Prometheus metrics.""" """Handle request for Prometheus metrics."""
_LOGGER.debug("Received Prometheus metrics request") _LOGGER.debug("Received Prometheus metrics request")
return web.Response( return web.Response(
body=self.prometheus_cli.generate_latest(self.prometheus_cli.REGISTRY), body=prometheus_client.generate_latest(prometheus_client.REGISTRY),
content_type=CONTENT_TYPE_TEXT_PLAIN, content_type=CONTENT_TYPE_TEXT_PLAIN,
) )