From 7c409fa32e71f2d55e01548bf261af1a84deab15 Mon Sep 17 00:00:00 2001 From: Arun Kumar Jain K Date: Tue, 10 Nov 2026 22:39:30 +0530 Subject: [PATCH 1/2] Add asynchronous Prometheus client --- README.md | 48 ++ docs/source/prometheus_api_client.rst | 8 + prometheus_api_client/__init__.py | 3 + .../async_prometheus_connect.py | 552 ++++++++++++++++++ requirements-core.txt | 1 + requirements.txt | 1 + tests/test_async_prometheus_connect.py | 459 +++++++++++++++ 7 files changed, 1072 insertions(+) create mode 100644 prometheus_api_client/async_prometheus_connect.py create mode 100644 tests/test_async_prometheus_connect.py diff --git a/README.md b/README.md index 75fb38a..6bd470e 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,54 @@ metric_df.head() """ ``` +#### Asynchronous Prometheus Client + +The library also provides `AsyncPrometheusConnect` for applications that use Python's asyncio event loop. It uses aiohttp to perform non-blocking HTTP requests. + +```python +import asyncio +from prometheus_api_client import AsyncPrometheusConnect + +async def main(): + async with AsyncPrometheusConnect( + url="http://localhost:9090" + ) as prom: + # Check the Prometheus connection + connected = await prom.check_prometheus_connection() + print("Connected:", connected) + + # Fetch all metric names + metrics = await prom.all_metrics() + print(metrics) + + # Execute an instant PromQL query + result = await prom.custom_query( + query="up" + ) + print(result) + +asyncio.run(main()) +``` + +You can also execute range queries and retrieve metric data asynchronously: + +```python +from datetime import datetime, timedelta, timezone + +async def fetch_range(prom): + end_time = datetime.now(timezone.utc) + start_time = end_time - timedelta(hours=1) + + result = await prom.custom_query_range( + query="up", + start_time=start_time, + end_time=end_time, + step="15", + ) + return result +``` + +`AsyncPrometheusConnect` supports asynchronous context management. If you don't use `async with`, close the client explicitly with `await prom.close()` when finished. For more functions included in the `prometheus-api-client` library, please refer to this [documentation.](https://prometheus-api-client-python.readthedocs.io/en/master/source/prometheus_api_client.html) diff --git a/docs/source/prometheus_api_client.rst b/docs/source/prometheus_api_client.rst index 720ab4a..9b2e04a 100644 --- a/docs/source/prometheus_api_client.rst +++ b/docs/source/prometheus_api_client.rst @@ -29,6 +29,14 @@ prometheus\_api\_client.prometheus\_connect module :undoc-members: :show-inheritance: +prometheus_api_client.async_prometheus_connect module +------------------------------------------------------ + +.. automodule:: prometheus_api_client.async_prometheus_connect + :members: + :undoc-members: + :show-inheritance: + prometheus\_api\_client.exceptions module -------------------------------------------------- diff --git a/prometheus_api_client/__init__.py b/prometheus_api_client/__init__.py index fa01176..296fef7 100644 --- a/prometheus_api_client/__init__.py +++ b/prometheus_api_client/__init__.py @@ -8,6 +8,9 @@ def __getattr__(name): if name == "PrometheusConnect": from .prometheus_connect import PrometheusConnect return PrometheusConnect + elif name == "AsyncPrometheusConnect": + from .async_prometheus_connect import AsyncPrometheusConnect + return AsyncPrometheusConnect elif name == "Metric": from .metric import Metric return Metric diff --git a/prometheus_api_client/async_prometheus_connect.py b/prometheus_api_client/async_prometheus_connect.py new file mode 100644 index 0000000..c36f7ca --- /dev/null +++ b/prometheus_api_client/async_prometheus_connect.py @@ -0,0 +1,552 @@ +"""Asynchronous client for collecting metrics from a Prometheus host.""" + +from datetime import datetime, timedelta +from typing import Optional +from urllib.parse import urlparse + +import aiohttp +import asyncio +import bz2 +import math +import os + +from .exceptions import PrometheusApiClientException + + +class AsyncPrometheusConnect: + """ + An asynchronous client for the Prometheus HTTP API. + + The HTTP session is created lazily on the first request. + + :param url: URL of the Prometheus host. + :param headers: Optional HTTP headers. + :param disable_ssl: Disable SSL certificate verification when True. + :param auth: Optional aiohttp.BasicAuth instance or (username, password) tuple. + :param proxy: Optional proxy dictionary. + :param timeout: Optional request timeout in seconds. + :param method: HTTP method (GET or POST) for query APIs. + :param retry: Number of retries for transient request failures. + :param retry_backoff_factor: Base delay in seconds between retries. + """ + + def __init__( + self, + url: str = "http://127.0.0.1:9090", + headers: Optional[dict] = None, + disable_ssl: bool = False, + auth=None, + proxy: Optional[dict] = None, + timeout: Optional[float] = None, + method: str = "GET", + retry: int = 3, + retry_backoff_factor: float = 1.0, + ): + if url is None: + raise TypeError("missing url") + + if not isinstance(url, str): + raise TypeError("url must be a string") + + if not isinstance(method, str): + raise TypeError("Method must be a string") + + method = method.upper() + if method not in {"GET", "POST"}: + raise ValueError("Method can only be GET or POST") + + if isinstance(retry, bool) or not isinstance(retry, int) or retry < 0: + raise ValueError("retry must be a non-negative integer") + + if ( + isinstance(retry_backoff_factor, bool) + or not isinstance(retry_backoff_factor, (int, float)) + or not math.isfinite(retry_backoff_factor) + or retry_backoff_factor < 0 + ): + raise ValueError("retry_backoff_factor must be a finite, non-negative number") + + if timeout is not None and ( + isinstance(timeout, bool) + or not isinstance(timeout, (int, float)) + or not math.isfinite(timeout) + or timeout < 0 + ): + raise ValueError("timeout must be a finite, non-negative number") + + self.url = url.rstrip("/") + self.prometheus_host = urlparse(self.url).netloc + self.headers = headers + self.disable_ssl = disable_ssl + self.auth = auth + self.proxy = proxy + self._timeout = timeout + self._method = method + self._retry = retry + self._retry_backoff_factor = retry_backoff_factor + self._retry_statuses = {408, 429, 500, 502, 503, 504} + self._session = None + self._all_metrics = None + + async def _get_session(self): + """Create and return the aiohttp session when needed.""" + if self._session is None or self._session.closed: + self._session = aiohttp.ClientSession() + return self._session + + def _get_auth(self): + """Convert a username/password tuple to aiohttp.BasicAuth.""" + if isinstance(self.auth, tuple): + return aiohttp.BasicAuth(*self.auth) + return self.auth + + def _get_proxy(self): + """Select the configured proxy for the Prometheus URL scheme.""" + if not self.proxy: + return None + + scheme = urlparse(self.url).scheme + return self.proxy.get( + scheme, + self.proxy.get( + "{}_proxy".format(scheme), + self.proxy.get("all"), + ), + ) + + async def _request(self, endpoint: str, params: dict, timeout=None, method=None): + """Perform an asynchronous request with retry support.""" + session = await self._get_session() + + request_timeout = self._timeout if timeout is None else timeout + + if request_timeout is not None and ( + isinstance(request_timeout, bool) + or not isinstance(request_timeout, (int, float)) + or not math.isfinite(request_timeout) + or request_timeout < 0 + ): + raise ValueError("timeout must be a finite, non-negative number") + + if request_timeout is not None: + request_timeout = aiohttp.ClientTimeout(total=request_timeout) + + request_method = method or self._method + request_url = "{}/api/v1/{}".format(self.url, endpoint) + + for attempt in range(self._retry + 1): + retry_delay = None + + try: + async with session.request( + method=request_method, + url=request_url, + params=params, + headers=self.headers, + auth=self._get_auth(), + proxy=self._get_proxy(), + ssl=not self.disable_ssl, + timeout=request_timeout, + ) as response: + if response.status == 200: + payload = await response.json() + data = payload["data"] + + if isinstance(data, dict) and "result" in data: + return data["result"] + + return data + + response_content = await response.read() + + if response.status in self._retry_statuses and attempt < self._retry: + retry_delay = self._retry_backoff_factor * (2**attempt) + else: + raise PrometheusApiClientException( + "HTTP Status Code {} ({!r})".format(response.status, response_content) + ) + + except (aiohttp.ClientError, asyncio.TimeoutError): + if attempt >= self._retry: + raise + + retry_delay = self._retry_backoff_factor * (2**attempt) + + if retry_delay is not None: + await asyncio.sleep(retry_delay) + + async def custom_query(self, query: str, params: Optional[dict] = None, timeout=None): + """ + Send an instant PromQL query asynchronously. + + :param query: PromQL expression. + :param params: Optional additional HTTP query parameters. + :param timeout: Optional request timeout in seconds. + :returns: List of metric results. + """ + request_params = { + **(params or {}), + "query": str(query), + } + return await self._request("query", request_params, timeout) + + async def custom_query_range( + self, + query: str, + start_time: datetime, + end_time: datetime, + step: str, + params: Optional[dict] = None, + timeout=None, + ): + """ + Send a range PromQL query asynchronously. + + :param query: PromQL expression. + :param start_time: Range start datetime. + :param end_time: Range end datetime. + :param step: Query resolution step. + :param params: Optional additional HTTP query parameters. + :param timeout: Optional request timeout in seconds. + :returns: List of metric results. + """ + request_params = { + **(params or {}), + "query": str(query), + "start": round(start_time.timestamp()), + "end": round(end_time.timestamp()), + "step": step, + } + return await self._request("query_range", request_params, timeout) + + async def check_prometheus_connection(self, params: dict = None) -> bool: + """Check whether the Prometheus endpoint is reachable.""" + session = await self._get_session() + + request_timeout = self._timeout + if request_timeout is not None: + request_timeout = aiohttp.ClientTimeout(total=request_timeout) + + async with session.request( + method="GET", + url="{}/".format(self.url), + headers=self.headers, + params=params, + auth=self._get_auth(), + proxy=self._get_proxy(), + ssl=not self.disable_ssl, + timeout=request_timeout, + ) as response: + return response.ok + + async def all_metrics(self, params: dict = None): + """Get all metric names scraped by Prometheus.""" + self._all_metrics = await self.get_label_values(label_name="__name__", params=params) + return self._all_metrics + + async def get_series(self, start: datetime, end: datetime, params: dict = None): + """Get series between the supplied start and end times.""" + request_params = { + **(params or {}), + "start": start.timestamp(), + "end": end.timestamp(), + } + return await self._request( + "series", + request_params, + method="GET", + ) + + async def get_label_names(self, params: dict = None): + """Get all label names.""" + return await self._request("labels", params or {}) + + async def get_label_values(self, label_name: str, params: dict = None): + """Get all values for a label.""" + return await self._request("label/{}/values".format(label_name), params or {}, method="GET") + + async def get_current_metric_value( + self, metric_name: str, label_config: dict = None, params: dict = None + ): + """Get the current value of a metric with optional label filters.""" + if label_config: + label_list = ["{}='{}'".format(key, label_config[key]) for key in label_config] + query = "{}{{{}}}".format(metric_name, ",".join(label_list)) + else: + query = metric_name + + return await self.custom_query(query=query, params=params) + + async def get_metric_range_data( + self, + metric_name: str, + label_config: dict = None, + start_time: datetime = None, + end_time: datetime = None, + chunk_size: timedelta = None, + store_locally: bool = False, + params: dict = None, + ): + """Get metric values over a time range, optionally in chunks.""" + params = params or {} + data = [] + + if start_time is None: + start_time = datetime.now() - timedelta(minutes=10) + if end_time is None: + end_time = datetime.now() + + if not (isinstance(start_time, datetime) and isinstance(end_time, datetime)): + raise TypeError("start_time and end_time can only be of type datetime.datetime") + + if chunk_size is None: + chunk_size = end_time - start_time + + if not isinstance(chunk_size, timedelta): + raise TypeError("chunk_size can only be of type datetime.timedelta") + + if end_time < start_time: + raise ValueError("end_time must not be before start_time") + + if (end_time - start_time).total_seconds() < chunk_size.total_seconds(): + raise ValueError("specified chunk_size is too big") + + chunk_seconds = round(chunk_size.total_seconds()) + if chunk_seconds <= 0: + raise ValueError("chunk_size must be greater than zero") + + start = round(start_time.timestamp()) + end = round(end_time.timestamp()) + + if label_config: + label_list = ["{}='{}'".format(key, label_config[key]) for key in label_config] + query = "{}{{{}}}".format(metric_name, ",".join(label_list)) + else: + query = metric_name + + while start < end: + current_chunk = min(chunk_seconds, end - start) + + result = await self.custom_query( + query=query + "[{}s]".format(current_chunk), + params={ + **params, + "time": start + current_chunk, + }, + ) + + data.extend(result) + + if store_locally: + import json + + self._store_metric_values_local( + metric_name, + json.dumps(result), + start + current_chunk, + ) + + start += current_chunk + + return data + + async def get_metric_aggregation( + self, + query: str, + operations: list, + start_time: datetime = None, + end_time: datetime = None, + step: str = "15", + params: dict = None, + ): + """Get aggregations on metric values received from a PromQL query.""" + try: + import numpy + except ImportError as e: + raise ImportError( + "NumPy is required for metric aggregation operations. " + "Please install it with: pip install prometheus-api-client[analytics] " + "or pip install prometheus-api-client[all]" + ) from e + + if not isinstance(operations, list): + raise TypeError("Operations can be only of type list") + + if len(operations) == 0: + return None + + query_values = [] + + if start_time is not None and end_time is not None: + data = await self.custom_query_range( + query=query, + params=params, + start_time=start_time, + end_time=end_time, + step=step, + ) + for result in data: + for value in result["values"]: + query_values.append(float(value[1])) + else: + data = await self.custom_query(query, params) + for result in data: + query_values.append(float(result["value"][1])) + + if not query_values: + return None + + np_array = numpy.array(query_values) + aggregated_values = {} + + for operation in operations: + if operation == "sum": + aggregated_values["sum"] = numpy.sum(np_array) + elif operation == "max": + aggregated_values["max"] = numpy.max(np_array) + elif operation == "min": + aggregated_values["min"] = numpy.min(np_array) + elif operation == "average": + aggregated_values["average"] = numpy.average(np_array) + elif operation.startswith("percentile"): + percentile = float(operation.split("_")[1]) + aggregated_values["percentile_" + str(percentile)] = numpy.percentile( + query_values, percentile + ) + elif operation == "deviation": + aggregated_values["deviation"] = numpy.std(np_array) + elif operation == "variance": + aggregated_values["variance"] = numpy.var(np_array) + else: + raise TypeError("Invalid operation: " + operation) + + return aggregated_values + + async def get_scrape_pools(self): + """Get a list of all scrape pools in active targets.""" + targets = await self.get_targets() + return list({target["scrapePool"] for target in targets["activeTargets"]}) + + async def get_targets(self, state: str = None, scrape_pool: str = None): + """ + Get targets from Prometheus. + + :param state: Optional target state ('active', 'dropped', or 'any'). + :param scrape_pool: Optional scrape pool name. + :returns: Dictionary containing active and dropped targets. + """ + params = {} + + if state: + params["state"] = state + + if scrape_pool: + params["scrapePool"] = scrape_pool + + return await self._request("targets", params, method="GET") + + async def get_target_metadata(self, target: dict, metric: str = None): + """ + Get metadata about metrics from a specific target. + + :param target: Target labels to match. + :param metric: Optional metric name filter. + :returns: List of matching metadata entries. + """ + params = {} + + if metric: + params["metric"] = metric + + if target: + match_target = "{" + ",".join(f'{key}="{value}"' for key, value in target.items()) + "}" + params["match_target"] = match_target + + return await self._request("targets/metadata", params, method="GET") + + async def get_metric_metadata( + self, metric: str = None, limit: int = None, limit_per_metric: int = None + ): + """ + Get metadata about metrics. + + :param metric: Optional metric name filter. + :param limit: Optional maximum number of metrics. + :param limit_per_metric: Optional maximum entries per metric. + :returns: List of formatted metadata entries. + """ + params = {} + + if metric: + params["metric"] = metric + + if limit: + params["limit"] = limit + + if limit_per_metric: + params["limit_per_metric"] = limit_per_metric + + data = await self._request("metadata", params, method="GET") + + formatted_data = [] + + for metric_name, entries in data.items(): + for entry in entries: + formatted_data.append( + { + "metric_name": metric_name, + "type": entry.get("type", "unknown"), + "help": entry.get("help", ""), + "unit": entry.get("unit", ""), + } + ) + + return formatted_data + + def _store_metric_values_local(self, metric_name, values, end_timestamp, compressed=False): + """Store metric values locally, optionally using bz2 compression.""" + if not values: + return None + + file_path = self._metric_filename(metric_name, end_timestamp) + + if compressed: + payload = bz2.compress(str(values).encode("utf-8")) + file_path += ".bz2" + else: + payload = str(values).encode("utf-8") + + os.makedirs(os.path.dirname(file_path), exist_ok=True) + + with open(file_path, "wb") as file: + file.write(payload) + + return file_path + + def _metric_filename(self, metric_name: str, end_timestamp: int): + """Generate the local metric filename.""" + end_time_stamp = datetime.fromtimestamp(end_timestamp) + directory_name = end_time_stamp.strftime("%Y%m%d") + timestamp = end_time_stamp.strftime("%Y%m%d%H%M") + + return os.path.join( + ".", + "metrics", + self.prometheus_host, + metric_name, + directory_name, + timestamp + ".json", + ) + + async def close(self): + """Close the underlying HTTP session.""" + if self._session is not None and not self._session.closed: + await self._session.close() + + async def __aenter__(self): + """Support async context-manager usage.""" + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + """Close the session when leaving the async context.""" + await self.close() diff --git a/requirements-core.txt b/requirements-core.txt index bbfd6bf..7455f9a 100644 --- a/requirements-core.txt +++ b/requirements-core.txt @@ -1,2 +1,3 @@ requests dateparser +aiohttp>=3.9,<4 diff --git a/requirements.txt b/requirements.txt index 5b71c01..6fe0429 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,3 +4,4 @@ pandas>=1.4.0 numpy matplotlib httmock +aiohttp>=3.9,<4 diff --git a/tests/test_async_prometheus_connect.py b/tests/test_async_prometheus_connect.py new file mode 100644 index 0000000..ac7685c --- /dev/null +++ b/tests/test_async_prometheus_connect.py @@ -0,0 +1,459 @@ +import unittest +from datetime import datetime, timedelta, timezone + +from aiohttp import web +from aiohttp.test_utils import TestServer + +from prometheus_api_client import AsyncPrometheusConnect +from prometheus_api_client.exceptions import PrometheusApiClientException + + +class TestAsyncPrometheusConnect(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self): + self.requests = [] + self.retry_attempts = 0 + + async def handler(request): + self.requests.append(request) + + if request.path == "/": + return web.Response(status=200) + + if request.query.get("query") == "retry_query": + self.retry_attempts += 1 + + if self.retry_attempts == 1: + return web.Response(status=503) + + return web.json_response( + { + "status": "success", + "data": { + "resultType": "vector", + "result": [{"value": 1}], + }, + } + ) + + if request.query.get("query") == "bad_query": + return web.json_response( + {"status": "error", "error": "bad query"}, + status=400, + ) + + if request.path.endswith("/api/v1/query") and "[" in request.query.get("query", ""): + return web.json_response( + { + "status": "success", + "data": { + "resultType": "vector", + "result": [{"metric": {"__name__": "up"}, "value": [1, "1"]}], + }, + } + ) + + if request.path.endswith("/api/v1/query"): + if request.query.get("query") == "aggregation_query": + return web.json_response( + { + "status": "success", + "data": { + "resultType": "vector", + "result": [ + {"metric": {"__name__": "up"}, "value": [1, "10"]}, + {"metric": {"__name__": "up"}, "value": [2, "20"]}, + {"metric": {"__name__": "up"}, "value": [3, "30"]}, + ], + }, + } + ) + + return web.json_response( + { + "status": "success", + "data": {"resultType": "vector", "result": [{"value": 1}]}, + } + ) + + if request.path.endswith("/api/v1/query_range"): + return web.json_response( + { + "status": "success", + "data": { + "resultType": "matrix", + "result": [{"values": [[1, "10"], [2, "20"], [3, "30"]]}], + }, + } + ) + + if request.path.endswith("/api/v1/labels"): + return web.json_response( + { + "status": "success", + "data": ["job", "instance"], + } + ) + + if request.path.endswith("/api/v1/label/__name__/values"): + return web.json_response( + { + "status": "success", + "data": ["up", "process_cpu_seconds_total"], + } + ) + + if request.path.endswith("/api/v1/series"): + return web.json_response( + { + "status": "success", + "data": [{"__name__": "up", "job": "prometheus"}], + } + ) + + if request.path.endswith("/api/v1/targets/metadata"): + return web.json_response( + { + "status": "success", + "data": [ + {"metric": "up", "type": "gauge"}, + ], + } + ) + + if request.path.endswith("/api/v1/targets"): + return web.json_response( + { + "status": "success", + "data": { + "activeTargets": [ + {"scrapePool": "prometheus"}, + {"scrapePool": "node"}, + ], + "droppedTargets": [], + }, + } + ) + + if request.path.endswith("/api/v1/metadata"): + return web.json_response( + { + "status": "success", + "data": { + "up": [ + { + "type": "gauge", + "help": "Target is up", + "unit": "", + } + ] + }, + } + ) + + return web.Response(status=404) + + app = web.Application() + app.router.add_route("*", "/{tail:.*}", handler) + + self.server = TestServer(app) + await self.server.start_server() + + self.prom = AsyncPrometheusConnect(url=str(self.server.make_url(""))) + + async def asyncTearDown(self): + await self.prom.close() + await self.server.close() + + async def test_check_prometheus_connection(self): + result = await self.prom.check_prometheus_connection() + self.assertTrue(result) + + async def test_all_metrics(self): + result = await self.prom.all_metrics() + self.assertEqual(result, ["up", "process_cpu_seconds_total"]) + + async def test_get_series(self): + start = datetime(2026, 1, 1, tzinfo=timezone.utc) + end = datetime(2026, 1, 2, tzinfo=timezone.utc) + + result = await self.prom.get_series(start, end) + + self.assertEqual(result[0]["__name__"], "up") + self.assertIn("start", self.requests[-1].query) + self.assertIn("end", self.requests[-1].query) + + async def test_get_label_names(self): + result = await self.prom.get_label_names() + self.assertEqual(result, ["job", "instance"]) + + async def test_get_label_values(self): + result = await self.prom.get_label_values("__name__") + self.assertEqual(result, ["up", "process_cpu_seconds_total"]) + + async def test_get_label_values_uses_get(self): + await self.prom.get_label_values("__name__") + self.assertEqual(self.requests[-1].method, "GET") + + async def test_get_current_metric_value(self): + result = await self.prom.get_current_metric_value("up") + self.assertEqual(result, [{"value": 1}]) + + async def test_http_error(self): + with self.assertRaises(PrometheusApiClientException): + await self.prom.custom_query("bad_query") + + async def test_get_metric_range_data(self): + start = datetime(2026, 1, 1, tzinfo=timezone.utc) + end = datetime(2026, 1, 1, 0, 2, tzinfo=timezone.utc) + + result = await self.prom.get_metric_range_data( + metric_name="up", + start_time=start, + end_time=end, + chunk_size=timedelta(minutes=1), + ) + + self.assertEqual(len(result), 2) + + async def test_get_metric_range_data_invalid_chunk(self): + start = datetime(2026, 1, 1, tzinfo=timezone.utc) + end = datetime(2026, 1, 1, 0, 2, tzinfo=timezone.utc) + + with self.assertRaises(ValueError): + await self.prom.get_metric_range_data( + metric_name="up", + start_time=start, + end_time=end, + chunk_size=timedelta(minutes=3), + ) + + async def test_get_targets(self): + result = await self.prom.get_targets(state="active") + self.assertEqual(len(result["activeTargets"]), 2) + self.assertEqual(self.requests[-1].query["state"], "active") + + async def test_get_scrape_pools(self): + result = await self.prom.get_scrape_pools() + self.assertEqual(set(result), {"prometheus", "node"}) + + async def test_get_target_metadata(self): + result = await self.prom.get_target_metadata({"job": "prometheus"}, metric="up") + self.assertEqual(result[0]["metric"], "up") + self.assertEqual( + self.requests[-1].query["match_target"], + '{job="prometheus"}', + ) + + async def test_get_metric_metadata(self): + result = await self.prom.get_metric_metadata(metric="up") + self.assertEqual( + result, + [ + { + "metric_name": "up", + "type": "gauge", + "help": "Target is up", + "unit": "", + } + ], + ) + + async def test_retries_on_server_error(self): + client = AsyncPrometheusConnect( + url=str(self.server.make_url("")), + retry=1, + retry_backoff_factor=0, + ) + + try: + result = await client.custom_query("retry_query") + + self.assertEqual(result, [{"value": 1}]) + self.assertEqual(self.retry_attempts, 2) + finally: + await client.close() + + async def test_get_metric_aggregation_instant_query(self): + result = await self.prom.get_metric_aggregation( + query="aggregation_query", + operations=["sum", "max", "min", "average", "deviation", "variance", "percentile_50"], + ) + + self.assertEqual(result["sum"], 60) + self.assertEqual(result["max"], 30) + self.assertEqual(result["min"], 10) + self.assertEqual(result["average"], 20) + self.assertEqual(result["percentile_50.0"], 20) + self.assertAlmostEqual(result["deviation"], 8.16496580927726) + self.assertAlmostEqual(result["variance"], 66.66666666666667) + + async def test_get_metric_aggregation_range_query(self): + start = datetime(2026, 1, 1, tzinfo=timezone.utc) + end = datetime(2026, 1, 2, tzinfo=timezone.utc) + + result = await self.prom.get_metric_aggregation( + query="aggregation_query", + operations=["sum", "average"], + start_time=start, + end_time=end, + ) + + self.assertEqual(result["sum"], 60) + self.assertEqual(result["average"], 20) + + async def test_get_metric_aggregation_empty_operations(self): + result = await self.prom.get_metric_aggregation( + query="up", + operations=[], + ) + + self.assertIsNone(result) + + async def test_get_metric_aggregation_invalid_operation(self): + with self.assertRaises(TypeError): + await self.prom.get_metric_aggregation( + query="up", + operations=["invalid"], + ) + + async def test_get_metric_aggregation_invalid_operations_type(self): + with self.assertRaises(TypeError): + await self.prom.get_metric_aggregation( + query="up", + operations="sum", + ) + + async def test_session_created_lazily(self): + client = AsyncPrometheusConnect(url=str(self.server.make_url(""))) + + self.assertIsNone(client._session) + + try: + await client.custom_query("up") + self.assertIsNotNone(client._session) + self.assertFalse(client._session.closed) + finally: + await client.close() + + async def test_close_and_recreate_session(self): + await self.prom.custom_query("up") + original_session = self.prom._session + + await self.prom.close() + self.assertTrue(original_session.closed) + + await self.prom.custom_query("up") + + self.assertIsNot(self.prom._session, original_session) + self.assertFalse(self.prom._session.closed) + + async def test_async_context_manager_closes_session(self): + client = AsyncPrometheusConnect(url=str(self.server.make_url(""))) + + async with client as prom: + await prom.custom_query("up") + self.assertFalse(prom._session.closed) + + self.assertTrue(client._session.closed) + + async def test_constructor_validation(self): + invalid_options = [ + {"retry": True}, + {"retry": -1}, + {"retry_backoff_factor": -1}, + {"retry_backoff_factor": float("nan")}, + {"retry_backoff_factor": float("inf")}, + {"timeout": -1}, + {"timeout": float("inf")}, + ] + + for options in invalid_options: + with self.subTest(options=options): + with self.assertRaises(ValueError): + AsyncPrometheusConnect(**options) + + with self.assertRaises(TypeError): + AsyncPrometheusConnect(url=None) + + async def test_post_method(self): + client = AsyncPrometheusConnect( + url=str(self.server.make_url("")), + method="POST", + ) + + try: + await client.custom_query("up") + self.assertEqual(self.requests[-1].method, "POST") + finally: + await client.close() + + async def test_non_retryable_http_error_is_not_retried(self): + client = AsyncPrometheusConnect( + url=str(self.server.make_url("")), + retry=3, + retry_backoff_factor=0, + ) + + try: + request_count_before = len(self.requests) + + with self.assertRaises(PrometheusApiClientException): + await client.custom_query("bad_query") + + self.assertEqual( + len(self.requests) - request_count_before, + 1, + ) + finally: + await client.close() + + async def test_custom_query_does_not_allow_params_to_override_query(self): + await self.prom.custom_query( + "up", + params={"query": "different_query"}, + ) + + self.assertEqual(self.requests[-1].query["query"], "up") + + async def test_get_metric_range_data_rejects_zero_chunk_size(self): + start = datetime(2026, 1, 1, tzinfo=timezone.utc) + end = datetime(2026, 1, 1, 0, 2, tzinfo=timezone.utc) + + with self.assertRaises(ValueError): + await self.prom.get_metric_range_data( + metric_name="up", + start_time=start, + end_time=end, + chunk_size=timedelta(0), + ) + + async def test_get_series_uses_get_with_post_configuration(self): + client = AsyncPrometheusConnect( + url=str(self.server.make_url("")), + method="POST", + ) + + try: + start = datetime(2026, 1, 1, tzinfo=timezone.utc) + end = datetime(2026, 1, 2, tzinfo=timezone.utc) + + await client.get_series(start, end) + + self.assertEqual(self.requests[-1].method, "GET") + finally: + await client.close() + + async def test_request_rejects_invalid_timeout(self): + client = AsyncPrometheusConnect() + + try: + for timeout in (-1, float("inf"), float("nan"), True, "invalid"): + with self.subTest(timeout=timeout): + with self.assertRaises(ValueError): + await client._request("query", {}, timeout=timeout) + finally: + await client.close() + + +if __name__ == "__main__": + unittest.main() From 84b07a0fe901fe061e66e4231d22e02258a8c88d Mon Sep 17 00:00:00 2001 From: Arun Kumar Jain K Date: Wed, 11 Nov 2026 11:30:15 +0530 Subject: [PATCH 2/2] Improve async Prometheus client configuration --- README.md | 3 +- .../async_prometheus_connect.py | 72 +++++++++++----- requirements-core.txt | 1 - setup.py | 8 +- tests/test_lazy_imports.py | 83 +++++++++++++++---- 5 files changed, 126 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 6bd470e..32aa9c2 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ To install the latest release: `pip install prometheus-api-client` -To install with all optional dependencies (pandas, numpy, matplotlib): +To install with all optional dependencies (pandas, numpy, matplotlib, aiohttp): `pip install prometheus-api-client[all]` @@ -22,6 +22,7 @@ To install only specific extras: - For DataFrame support: `pip install prometheus-api-client[dataframe]` - For analytics/aggregation operations: `pip install prometheus-api-client[analytics]` - For plotting support: `pip install prometheus-api-client[plot]` +- For asynchronous Prometheus client support: `pip install prometheus-api-client[async]` To install directly from this branch: diff --git a/prometheus_api_client/async_prometheus_connect.py b/prometheus_api_client/async_prometheus_connect.py index c36f7ca..8990b73 100644 --- a/prometheus_api_client/async_prometheus_connect.py +++ b/prometheus_api_client/async_prometheus_connect.py @@ -4,7 +4,14 @@ from typing import Optional from urllib.parse import urlparse -import aiohttp +try: + import aiohttp +except ImportError as exc: + raise ImportError( + "aiohttp is required for AsyncPrometheusConnect. " + "Install it with: pip install prometheus-api-client[async]" + ) from exc + import asyncio import bz2 import math @@ -22,6 +29,8 @@ class AsyncPrometheusConnect: :param url: URL of the Prometheus host. :param headers: Optional HTTP headers. :param disable_ssl: Disable SSL certificate verification when True. + :param ssl_context: Optional ssl.SSLContext for custom CA or client + certificate configuration. :param auth: Optional aiohttp.BasicAuth instance or (username, password) tuple. :param proxy: Optional proxy dictionary. :param timeout: Optional request timeout in seconds. @@ -35,6 +44,7 @@ def __init__( url: str = "http://127.0.0.1:9090", headers: Optional[dict] = None, disable_ssl: bool = False, + ssl_context=None, auth=None, proxy: Optional[dict] = None, timeout: Optional[float] = None, @@ -42,6 +52,7 @@ def __init__( retry: int = 3, retry_backoff_factor: float = 1.0, ): + """Initialize the asynchronous Prometheus client.""" if url is None: raise TypeError("missing url") @@ -70,14 +81,15 @@ def __init__( isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not math.isfinite(timeout) - or timeout < 0 + or timeout <= 0 ): - raise ValueError("timeout must be a finite, non-negative number") + raise ValueError("timeout must be a finite, positive number") self.url = url.rstrip("/") self.prometheus_host = urlparse(self.url).netloc self.headers = headers self.disable_ssl = disable_ssl + self.ssl_context = ssl_context self.auth = auth self.proxy = proxy self._timeout = timeout @@ -91,7 +103,7 @@ def __init__( async def _get_session(self): """Create and return the aiohttp session when needed.""" if self._session is None or self._session.closed: - self._session = aiohttp.ClientSession() + self._session = aiohttp.ClientSession(trust_env=True) return self._session def _get_auth(self): @@ -101,19 +113,28 @@ def _get_auth(self): return self.auth def _get_proxy(self): - """Select the configured proxy for the Prometheus URL scheme.""" + """Select the configured proxy for the Prometheus URL.""" if not self.proxy: return None - scheme = urlparse(self.url).scheme - return self.proxy.get( + parsed_url = urlparse(self.url) + scheme = parsed_url.scheme + host = parsed_url.netloc + + proxy_keys = ( + "{}://{}".format(scheme, host), scheme, - self.proxy.get( - "{}_proxy".format(scheme), - self.proxy.get("all"), - ), + "all://{}".format(host), + "all", + "{}_proxy".format(scheme), ) + for key in proxy_keys: + if key in self.proxy: + return self.proxy[key] + + return None + async def _request(self, endpoint: str, params: dict, timeout=None, method=None): """Perform an asynchronous request with retry support.""" session = await self._get_session() @@ -124,12 +145,13 @@ async def _request(self, endpoint: str, params: dict, timeout=None, method=None) isinstance(request_timeout, bool) or not isinstance(request_timeout, (int, float)) or not math.isfinite(request_timeout) - or request_timeout < 0 + or request_timeout <= 0 ): - raise ValueError("timeout must be a finite, non-negative number") + raise ValueError("timeout must be a finite, positive number") + request_kwargs = {} if request_timeout is not None: - request_timeout = aiohttp.ClientTimeout(total=request_timeout) + request_kwargs["timeout"] = aiohttp.ClientTimeout(total=request_timeout) request_method = method or self._method request_url = "{}/api/v1/{}".format(self.url, endpoint) @@ -145,8 +167,10 @@ async def _request(self, endpoint: str, params: dict, timeout=None, method=None) headers=self.headers, auth=self._get_auth(), proxy=self._get_proxy(), - ssl=not self.disable_ssl, - timeout=request_timeout, + ssl=( + self.ssl_context if self.ssl_context is not None else not self.disable_ssl + ), + **request_kwargs, ) as response: if response.status == 200: payload = await response.json() @@ -223,9 +247,9 @@ async def check_prometheus_connection(self, params: dict = None) -> bool: """Check whether the Prometheus endpoint is reachable.""" session = await self._get_session() - request_timeout = self._timeout - if request_timeout is not None: - request_timeout = aiohttp.ClientTimeout(total=request_timeout) + request_kwargs = {} + if self._timeout is not None: + request_kwargs["timeout"] = aiohttp.ClientTimeout(total=self._timeout) async with session.request( method="GET", @@ -234,8 +258,8 @@ async def check_prometheus_connection(self, params: dict = None) -> bool: params=params, auth=self._get_auth(), proxy=self._get_proxy(), - ssl=not self.disable_ssl, - timeout=request_timeout, + ssl=(self.ssl_context if self.ssl_context is not None else not self.disable_ssl), + **request_kwargs, ) as response: return response.ok @@ -263,7 +287,11 @@ async def get_label_names(self, params: dict = None): async def get_label_values(self, label_name: str, params: dict = None): """Get all values for a label.""" - return await self._request("label/{}/values".format(label_name), params or {}, method="GET") + return await self._request( + "label/{}/values".format(label_name), + params or {}, + method="GET", + ) async def get_current_metric_value( self, metric_name: str, label_config: dict = None, params: dict = None diff --git a/requirements-core.txt b/requirements-core.txt index 7455f9a..bbfd6bf 100644 --- a/requirements-core.txt +++ b/requirements-core.txt @@ -1,3 +1,2 @@ requests dateparser -aiohttp>=3.9,<4 diff --git a/setup.py b/setup.py index 120d9ad..dd0678e 100644 --- a/setup.py +++ b/setup.py @@ -41,7 +41,13 @@ def get_version(): "numpy": ["numpy"], "plot": ["matplotlib"], "analytics": ["numpy"], - "all": ["pandas>=1.4.0", "numpy", "matplotlib"], + "async": ["aiohttp>=3.9,<4"], + "all": [ + "pandas>=1.4.0", + "numpy", + "matplotlib", + "aiohttp>=3.9,<4", + ], }, packages=setuptools.find_packages(), package_data={"prometheus-api-client": ["py.typed"]}, diff --git a/tests/test_lazy_imports.py b/tests/test_lazy_imports.py index bac80bf..26a1df6 100644 --- a/tests/test_lazy_imports.py +++ b/tests/test_lazy_imports.py @@ -1,28 +1,32 @@ """Test lazy imports to ensure pandas/matplotlib are not loaded unnecessarily.""" + import unittest import sys import subprocess class TestLazyImports(unittest.TestCase): - """Test that PrometheusConnect can be imported without loading heavy dependencies.""" + """Test that PrometheusConnect can be imported without loading + heavy dependencies. + """ def _run_in_subprocess(self, code, fail_map): """Run code in a subprocess and check exit codes against fail_map. - + Args: code: Python code to execute in subprocess fail_map: Dictionary mapping exit codes to error messages - + Raises: - AssertionError: If subprocess exits with a code in fail_map or any non-zero code + AssertionError: If subprocess exits with a code in fail_map + or any non-zero code """ result = subprocess.run( - [sys.executable, '-c', code], + [sys.executable, "-c", code], capture_output=True, - text=True + text=True, ) - + if result.returncode in fail_map: self.fail(fail_map[result.returncode]) elif result.returncode != 0: @@ -36,16 +40,27 @@ def _run_in_subprocess(self, code, fail_map): self.fail(f"Subprocess failed with code {result.returncode}: {output_str}") def test_prometheus_connect_import_without_pandas_matplotlib_numpy(self): - """Test that importing PrometheusConnect doesn't load pandas, matplotlib, or numpy.""" + """Test that importing PrometheusConnect doesn't load pandas, + matplotlib, or numpy. + """ # Run in a subprocess to avoid affecting other tests code = """ import sys from prometheus_api_client import PrometheusConnect # Check that pandas, matplotlib, and numpy are not loaded -pandas_loaded = any(m == 'pandas' or m.startswith('pandas.') for m in sys.modules.keys()) -matplotlib_loaded = any(m == 'matplotlib' or m.startswith('matplotlib.') for m in sys.modules.keys()) -numpy_loaded = any(m == 'numpy' or m.startswith('numpy.') for m in sys.modules.keys()) +pandas_loaded = any( + m == 'pandas' or m.startswith('pandas.') for m in sys.modules.keys() +) +matplotlib_loaded = any( + m == 'matplotlib' or m.startswith('matplotlib.') for m in sys.modules.keys() +) +numpy_loaded = any( + m == 'numpy' or m.startswith('numpy.') for m in sys.modules.keys() +) +aiohttp_loaded = any( + m == 'aiohttp' or m.startswith('aiohttp.') for m in sys.modules.keys() +) if pandas_loaded: sys.exit(1) @@ -53,15 +68,18 @@ def test_prometheus_connect_import_without_pandas_matplotlib_numpy(self): sys.exit(2) if numpy_loaded: sys.exit(3) +if aiohttp_loaded: + sys.exit(4) sys.exit(0) """ fail_map = { 1: "pandas should not be loaded when importing PrometheusConnect", 2: "matplotlib should not be loaded when importing PrometheusConnect", 3: "numpy should not be loaded when importing PrometheusConnect", + 4: "aiohttp should not be loaded when importing PrometheusConnect", } self._run_in_subprocess(code, fail_map) - + def test_prometheus_connect_instantiation_without_numpy(self): """Test that PrometheusConnect can be instantiated without loading numpy.""" # Run in a subprocess to avoid affecting other tests @@ -89,12 +107,45 @@ def test_prometheus_connect_instantiation_without_numpy(self): def test_metric_import_loads_pandas(self): """Test that importing Metric does load pandas (expected behavior).""" # This test doesn't remove modules, so it won't cause reload issues - from prometheus_api_client import Metric - + from prometheus_api_client import Metric # noqa: F401 + # Check that pandas is loaded (this is expected for Metric) - pandas_loaded = any(m == 'pandas' or m.startswith('pandas.') for m in sys.modules.keys()) + pandas_loaded = any(m == "pandas" or m.startswith("pandas.") for m in sys.modules.keys()) self.assertTrue(pandas_loaded, "pandas should be loaded when importing Metric") + def test_async_import_without_aiohttp_shows_install_message(self): + """Test that importing AsyncPrometheusConnect gives a helpful error + without aiohttp. + """ + code = """ +import builtins +import sys + +real_import = builtins.__import__ + +def blocked_import(name, *args, **kwargs): + if name == "aiohttp" or name.startswith("aiohttp."): + raise ImportError("aiohttp blocked for test") + return real_import(name, *args, **kwargs) + +builtins.__import__ = blocked_import + +try: + from prometheus_api_client import AsyncPrometheusConnect +except ImportError as exc: + if "pip install prometheus-api-client[async]" not in str(exc): + sys.exit(1) +else: + sys.exit(2) + +sys.exit(0) +""" + fail_map = { + 1: "The aiohttp import error should explain how to install the async extra", + 2: ("Importing AsyncPrometheusConnect should fail when " "aiohttp is unavailable"), + } + self._run_in_subprocess(code, fail_map) + -if __name__ == '__main__': +if __name__ == "__main__": unittest.main()