-
Notifications
You must be signed in to change notification settings - Fork 73
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Basic Prometheus metrics for API requests
- Loading branch information
Showing
10 changed files
with
155 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
from .redis_counter import RedisCounter, collect, metrics_enabled | ||
|
||
metric_api_requests = RedisCounter( | ||
"api_requests", "API request metrics", ("method", "endpoint", "user", "status_code") | ||
) | ||
|
||
__all__ = [ | ||
"collect", | ||
"metrics_enabled", | ||
"metric_api_requests", | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
from typing import Dict | ||
|
||
from prometheus_client import CollectorRegistry | ||
from prometheus_client import Gauge as PrometheusGauge | ||
from prometheus_client import generate_latest | ||
from redis import Redis | ||
|
||
from mwdb.core.config import app_config | ||
from mwdb.core.log import getLogger | ||
|
||
METRIC_REGISTRY = CollectorRegistry() | ||
METRIC_EXPIRATION_TIME = 24 * 60 * 60 | ||
COUNTERS = [] | ||
|
||
logger = getLogger() | ||
|
||
redis = None | ||
if app_config.mwdb.enable_prometheus_metrics: | ||
if not app_config.mwdb.redis_uri: | ||
logger.warning( | ||
"metrics: Prometheus metrics are disabled because redis_uri is not set" | ||
) | ||
redis = Redis.from_url(app_config.mwdb.redis_uri, decode_responses=True) | ||
|
||
|
||
class RedisCounter: | ||
KEY_PREFIX = "METRICS" | ||
|
||
def __init__(self, name, documentation, labelnames=()): | ||
self._gauge = PrometheusGauge( | ||
name, documentation, labelnames, registry=METRIC_REGISTRY | ||
) | ||
self._name = name | ||
self._labelnames = labelnames | ||
COUNTERS.append(self) | ||
|
||
def inc(self, amount: int = 1, **labelkwargs) -> None: | ||
if not redis: | ||
return | ||
redis_key = self._key_from_labelkwargs(**labelkwargs) | ||
p = redis.pipeline() | ||
p.incr(redis_key, amount) | ||
p.expire(redis_key, METRIC_EXPIRATION_TIME) | ||
p.execute() | ||
|
||
def _key_from_labelkwargs(self, **labelkwargs): | ||
elements = [labelkwargs[name].replace(":", "_") for name in self._labelnames] | ||
return ":".join([self.KEY_PREFIX, self._name] + elements) | ||
|
||
def _labelkwargs_from_key(self, key): | ||
parts = key.split(":") | ||
name, *elements = parts[1:] | ||
if name != self._name: | ||
return None | ||
if len(elements) != len(self._labelnames): | ||
logger.warning( | ||
f"metrics: Got {len(elements)} label parts " | ||
f"but expected {len(self._labelnames)}" | ||
) | ||
return None | ||
return {self._labelnames[idx]: value for idx, value in enumerate(elements)} | ||
|
||
def update_counters(self, counters: Dict[str, int]): | ||
""" | ||
This method updates counters based on | ||
""" | ||
self._gauge.clear() | ||
|
||
for key, value in counters.items(): | ||
labelkwargs = self._labelkwargs_from_key(key) | ||
if labelkwargs is None: | ||
return | ||
self._gauge.labels(**labelkwargs).set(value) | ||
|
||
|
||
def collect(): | ||
keys = redis.keys(f"{RedisCounter.KEY_PREFIX}:*") | ||
values = redis.mget(keys) | ||
counters = dict(zip(keys, values)) | ||
for counter in COUNTERS: | ||
counter.update_counters(counters) | ||
return generate_latest(METRIC_REGISTRY) | ||
|
||
|
||
def metrics_enabled(): | ||
return redis is not None |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
from flask import Response | ||
from flask_restful import Resource | ||
|
||
from mwdb.core.capabilities import Capabilities | ||
from mwdb.core.metrics import collect | ||
|
||
from . import requires_authorization, requires_capabilities | ||
|
||
|
||
class MetricsResource(Resource): | ||
@requires_authorization | ||
@requires_capabilities(Capabilities.access_prometheus_metrics) | ||
def get(self): | ||
""" | ||
--- | ||
summary: Get Prometheus metrics | ||
description: | | ||
Returns metrics for Prometheus. | ||
Requires 'access_prometheus_metrics' privilege | ||
security: | ||
- bearerAuth: [] | ||
tags: | ||
- metrics | ||
responses: | ||
200: | ||
description: Metrics in Prometheus format | ||
403: | ||
description: | | ||
User don't have 'access_prometheus_metrics' privilege. | ||
""" | ||
metrics = collect() | ||
return Response( | ||
metrics, | ||
content_type="application/octet-stream", | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -29,3 +29,4 @@ python-dateutil==2.8.2 | |
pyzipper==0.3.5 | ||
pycryptodomex==3.19.1 | ||
ssdeep==3.4 | ||
prometheus-client==0.19.0 |