Centralize fail2ban metadata resolution and cache DB path discovery

This commit is contained in:
2026-04-12 19:48:33 +02:00
parent e221cd414f
commit 72488b14b2
4 changed files with 189 additions and 18 deletions

View File

@@ -5,32 +5,24 @@ from __future__ import annotations
import json
from datetime import UTC, datetime
from app.services.fail2ban_metadata_service import default_fail2ban_metadata_service
def ts_to_iso(unix_ts: int) -> str:
"""Convert a Unix timestamp to an ISO 8601 UTC string."""
return datetime.fromtimestamp(unix_ts, tz=UTC).isoformat()
async def get_fail2ban_db_path(socket_path: str) -> str:
"""Query fail2ban for the path to its SQLite database file."""
from app.utils.fail2ban_client import Fail2BanClient # pragma: no cover
async def get_fail2ban_db_path(socket_path: str, *, force_refresh: bool = False) -> str:
"""Return the fail2ban database path, using cached metadata when available."""
return await default_fail2ban_metadata_service.get_db_path(
socket_path, force_refresh=force_refresh
)
socket_timeout: float = 5.0
async with Fail2BanClient(socket_path, timeout=socket_timeout) as client:
response = await client.send(["get", "dbfile"])
if not isinstance(response, tuple) or len(response) != 2:
raise RuntimeError(f"Unexpected response from fail2ban: {response!r}")
code, data = response
if code != 0:
raise RuntimeError(f"fail2ban error code {code}: {data!r}")
if data is None:
raise RuntimeError("fail2ban has no database configured (dbfile is None)")
return str(data)
def invalidate_fail2ban_db_path(socket_path: str) -> None:
"""Invalidate the cached fail2ban database path for the given socket."""
default_fail2ban_metadata_service.invalidate_db_path(socket_path)
def parse_data_json(raw: object) -> tuple[list[str], int]: