Skip to content

Commit

Permalink
Merge pull request #11 from Minei3oat/metrics
Browse files Browse the repository at this point in the history
Add prometheus metrics endpoint for nfregexes
  • Loading branch information
domysh authored Dec 15, 2024
2 parents a8dc0ba + 71d3019 commit 9ed5e1e
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion backend/routers/nfregex.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import re
import secrets
import sqlite3
from fastapi import APIRouter, HTTPException
from fastapi import APIRouter, Response, HTTPException
from pydantic import BaseModel
from modules.nfregex.nftables import FiregexTables
from modules.nfregex.firewall import STATUS, FirewallManager
Expand Down Expand Up @@ -275,3 +275,26 @@ async def add_new_service(form: ServiceAddForm):
await firewall.reload()
await refresh_frontend()
return {'status': 'ok', 'service_id': srv_id}

@app.get('/metrics', response_class = Response)
async def metrics():
"""Aggregate metrics"""
stats = db.query("""
SELECT
s.name,
s.status,
r.regex,
r.is_blacklist,
r.mode,
r.is_case_sensitive,
r.blocked_packets,
r.active
FROM regexes r LEFT JOIN services s ON s.service_id = r.service_id;
""")
metrics = []
sanitize = lambda s : s.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n')
for stat in stats:
props = f'service_name="{sanitize(stat["name"])}",regex="{sanitize(b64decode(stat["regex"]).decode())}",mode="{stat["mode"]}",is_case_sensitive="{stat["is_case_sensitive"]}"'
metrics.append(f'firegex_blocked_packets{{{props}}} {stat["blocked_packets"]}')
metrics.append(f'firegex_active{{{props}}} {int(stat["active"] and stat["status"] == "active")}')
return "\n".join(metrics)

0 comments on commit 9ed5e1e

Please sign in to comment.