|
1 | 1 | """Uptime Kuma client.""" |
2 | 2 |
|
3 | | -from aiohttp import ClientSession |
| 3 | +from http import HTTPStatus |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from aiohttp import ( |
| 7 | + BasicAuth, |
| 8 | + ClientError, |
| 9 | + ClientResponseError, |
| 10 | + ClientSession, |
| 11 | + ClientTimeout, |
| 12 | +) |
| 13 | +from prometheus_client.parser import text_string_to_metric_families |
4 | 14 | from yarl import URL |
5 | 15 |
|
6 | | -from .decorator import api_request |
7 | | -from .models import UptimeKumaApiResponse |
| 16 | +from .exceptions import UptimeKumaAuthenticationException, UptimeKumaConnectionException |
| 17 | +from .models import UptimeKumaMonitor |
8 | 18 |
|
9 | 19 |
|
10 | 20 | class UptimeKuma: |
11 | | - """This class is used to get information from Uptime Kuma.""" |
| 21 | + """Uptime Kuma client.""" |
12 | 22 |
|
13 | | - def __init__(self, session: ClientSession, base_url: URL | str, username: str, password: str) -> None: |
14 | | - """Initialize""" |
15 | | - self.monitors = [] |
| 23 | + def __init__( |
| 24 | + self, |
| 25 | + session: ClientSession, |
| 26 | + base_url: URL | str, |
| 27 | + api_key: str | None = None, |
| 28 | + timeout: float | None = None, |
| 29 | + ) -> None: |
| 30 | + """Initialize the Uptime Kuma client.""" |
16 | 31 | self._base_url = base_url if isinstance(base_url, URL) else URL(base_url) |
17 | | - self._username = username |
18 | | - self._password = password |
19 | | - self._session: ClientSession = session |
20 | 32 |
|
21 | | - @api_request("metrics") |
22 | | - async def async_get_monitors(self, **kwargs) -> UptimeKumaApiResponse: |
23 | | - """Get monitors from API.""" |
| 33 | + self._auth = BasicAuth("", api_key) if api_key else None |
| 34 | + |
| 35 | + self._timeout = ClientTimeout(total=timeout or 10) |
| 36 | + self._session = session |
| 37 | + |
| 38 | + async def metrics(self) -> list[UptimeKumaMonitor]: |
| 39 | + """Retrieve metrics from Uptime Kuma.""" |
| 40 | + url = self._base_url / "metrics" |
| 41 | + |
| 42 | + try: |
| 43 | + request = await self._session.get( |
| 44 | + url, auth=self._auth, timeout=self._timeout |
| 45 | + ) |
| 46 | + request.raise_for_status() |
| 47 | + except ClientResponseError as e: |
| 48 | + if e.status is HTTPStatus.UNAUTHORIZED: |
| 49 | + msg = "Authentication failed for %s" |
| 50 | + raise UptimeKumaAuthenticationException(msg, str(url)) from e |
| 51 | + msg = "Request for %s failed with status code %s" |
| 52 | + raise UptimeKumaConnectionException(msg, str(url), e.status) from e |
| 53 | + except TimeoutError as e: |
| 54 | + msg = "Request timeout for %s" |
| 55 | + raise UptimeKumaConnectionException(msg, str(url)) from e |
| 56 | + except ClientError as e: |
| 57 | + raise UptimeKumaConnectionException from e |
| 58 | + else: |
| 59 | + parsed = text_string_to_metric_families(await request.text()) |
| 60 | + |
| 61 | + monitors: dict[str, dict[str, Any]] = {} |
| 62 | + for metric in parsed: |
| 63 | + if not metric.name.startswith("monitor"): |
| 64 | + continue |
| 65 | + for sample in metric.samples: |
| 66 | + if not (monitor_name := sample.labels.get("monitor_name")): |
| 67 | + continue |
| 68 | + |
| 69 | + monitors.setdefault(monitor_name, sample.labels).update( |
| 70 | + {sample.name: sample.value} |
| 71 | + ) |
| 72 | + |
| 73 | + return { |
| 74 | + key: UptimeKumaMonitor.from_dict(value) |
| 75 | + for key, value in monitors.items() |
| 76 | + } |
0 commit comments