Skip to content
This repository was archived by the owner on Jan 13, 2025. It is now read-only.

Commit 11cfae9

Browse files
authored
Add support for exposing Prometheus metrics (#11)
* Add support for Prometheus metrics --------- Signed-off-by: hayk96 <hayko5999@gmail.com>
1 parent 512d76d commit 11cfae9

File tree

8 files changed

+39
-7
lines changed

8 files changed

+39
-7
lines changed

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## 0.1.5 / 2024-02-25
4+
5+
* [ENHANCEMENT] Added support for exposing Prometheus metrics. The corresponding metrics are available under the path
6+
`/api-metrics`. The `/metrics` endpoint is also accessible for exposing the metrics of the Prometheus server.
7+
* [BUGFIX] Fixed startup check of filesystem permissions in case of OSError.
8+
39
## 0.1.4 / 2024-01-28
410

511
* [ENHANCEMENT] Added HTTP query string: `recreate=true|false` for `PUT /api/v1/rules/{file}` endpoint.

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -146,9 +146,9 @@ required parameters:
146146
<!-- ROADMAP -->
147147
## Roadmap
148148

149-
- [ ] Add Prometheus instrumentation to expose metrics.
149+
- [x] Add Prometheus instrumentation to expose metrics.
150150
- [ ] Add a Bulk API to allow the creation of multiple rules via a single API call.
151-
- [ ] Implement a way to update existing rules through the API.
151+
- [x] Implement a way to update existing rules through the API.
152152

153153
<!-- CONTACT -->
154154
## Author and Maintainer

main.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from src.utils.arguments import arg_parser
33
from src.api.v1.api import api_router
44
from src.utils.openapi import openapi
5+
from src.utils.metrics import metrics
56
from src.utils.log import logger
67
from src.utils import settings
78
from fastapi import FastAPI
@@ -12,11 +13,11 @@
1213
prom_addr, rule_path = args.get("prom.addr"), args.get("rule.path")
1314
host, port = args.get("web.listen_address").split(":")
1415

15-
if False in [settings.check_prom_http_connection(prom_addr),
16+
if not all([settings.check_prom_http_connection(prom_addr),
1617
settings.check_reload_api_status(prom_addr),
1718
settings.check_rules_directory(rule_path),
1819
settings.check_fs_permissions(rule_path),
19-
rule_schema_status]:
20+
rule_schema_status]):
2021
sys.exit()
2122

2223

@@ -26,6 +27,7 @@ def custom_openapi_wrapper():
2627

2728
app = FastAPI(swagger_ui_parameters={"defaultModelsExpandDepth": -1})
2829
app.openapi = custom_openapi_wrapper
30+
metrics(app)
2931
app.include_router(api_router)
3032

3133

requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
prometheus-fastapi-instrumentator==6.1.0
12
python-json-logger==2.0.7
23
email-validator==2.0.0
34
fastapi==0.109.0

src/api/v1/endpoints/rules.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ async def update(
209209
return resp
210210

211211
response.status_code = status.HTTP_409_CONFLICT
212-
msg = f"The requested file already exists."
212+
msg = "The requested file already exists."
213213
logger.info(
214214
msg=msg,
215215
extra={

src/utils/metrics.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from prometheus_fastapi_instrumentator import PrometheusFastApiInstrumentator
2+
from fastapi import FastAPI
3+
from .log import logger
4+
from sys import modules
5+
6+
7+
def metrics(app: FastAPI):
8+
"""
9+
This function exposes Prometheus
10+
metrics for prometheus-api service
11+
"""
12+
metrics_path = "/api-metrics"
13+
try:
14+
instrumentator = PrometheusFastApiInstrumentator(
15+
should_group_status_codes=False,
16+
excluded_handlers=["/{path:path}", "/.*metrics"]
17+
)
18+
instrumentator.instrument(app)
19+
instrumentator.expose(app, endpoint=metrics_path, tags=["metrics"])
20+
except BaseException as e:
21+
logger.error(f"{modules[__name__], e}")
22+
else:
23+
logger.info(f"Successfully started metrics endpoint at {metrics_path} path")

src/utils/openapi.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def openapi(app: FastAPI):
1616
"providing additional features and addressing its limitations. "
1717
"Running as a sidecar alongside the Prometheus server enables "
1818
"users to extend the capabilities of the API.",
19-
version="0.1.4",
19+
version="0.1.5",
2020
contact={
2121
"name": "Hayk Davtyan",
2222
"url": "https://hayk96.github.io",

src/utils/settings.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def check_fs_permissions(prometheus_rules_dir) -> bool:
5757
except OSError as e:
5858
logger.error(
5959
f"The temporary file could not be created or deleted for testing permissions. {e}")
60-
return True
60+
return False
6161
else:
6262
logger.debug(
6363
"The application has the necessary permissions to access the rule files directory.")

0 commit comments

Comments
 (0)