Task 5: finalize config_file_service wrapper refactor and mark task done
This commit is contained in:
@@ -25,16 +25,7 @@ from app.exceptions import (
|
||||
JailNotFoundError,
|
||||
JailNotFoundInConfigError,
|
||||
)
|
||||
from app.services.config_file_service import (
|
||||
build_inactive_jail,
|
||||
get_active_jail_names,
|
||||
parse_jails_sync,
|
||||
safe_jail_name,
|
||||
start_daemon,
|
||||
validate_jail_config_sync,
|
||||
wait_for_fail2ban,
|
||||
)
|
||||
from app.services.jail_service import reload_all
|
||||
import app.services.config_file_service as config_file_service
|
||||
from app.models.config import (
|
||||
ActivateJailRequest,
|
||||
InactiveJail,
|
||||
@@ -221,23 +212,6 @@ def _validate_regex_patterns(patterns: list[str]) -> None:
|
||||
raise FilterInvalidRegexError(pattern, str(exc)) from exc
|
||||
|
||||
|
||||
async def _probe_fail2ban_running(socket_path: str) -> bool:
|
||||
"""Return ``True`` if the fail2ban socket responds to a ping.
|
||||
|
||||
Args:
|
||||
socket_path: Path to the fail2ban Unix domain socket.
|
||||
|
||||
Returns:
|
||||
``True`` when fail2ban is reachable, ``False`` otherwise.
|
||||
"""
|
||||
try:
|
||||
client = Fail2BanClient(socket_path=socket_path, timeout=5.0)
|
||||
resp = await client.send(["ping"])
|
||||
return isinstance(resp, (list, tuple)) and resp[0] == 0
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
# Shared functions from config_file_service are imported directly from the
|
||||
# canonical shared helper module.
|
||||
|
||||
@@ -270,11 +244,11 @@ async def list_inactive_jails(
|
||||
inactive jails.
|
||||
"""
|
||||
parsed_result: tuple[dict[str, dict[str, str]], dict[str, str]] = await run_blocking(
|
||||
parse_jails_sync,
|
||||
config_file_service._parse_jails_sync,
|
||||
Path(config_dir),
|
||||
)
|
||||
all_jails, source_files = parsed_result
|
||||
active_names: set[str] = await get_active_jail_names(socket_path)
|
||||
active_names: set[str] = await config_file_service._get_active_jail_names(socket_path)
|
||||
|
||||
inactive: list[InactiveJail] = []
|
||||
for jail_name, settings in sorted(all_jails.items()):
|
||||
@@ -283,7 +257,7 @@ async def list_inactive_jails(
|
||||
continue
|
||||
|
||||
source = source_files.get(jail_name, config_dir)
|
||||
inactive.append(build_inactive_jail(jail_name, settings, source, Path(config_dir)))
|
||||
inactive.append(config_file_service.build_inactive_jail(jail_name, settings, source, Path(config_dir)))
|
||||
|
||||
log.info(
|
||||
"inactive_jails_listed",
|
||||
@@ -353,21 +327,21 @@ async def _activate_jail(
|
||||
~app.utils.fail2ban_client.Fail2BanConnectionError: If the fail2ban
|
||||
socket is unreachable during reload.
|
||||
"""
|
||||
safe_jail_name(name)
|
||||
config_file_service.safe_jail_name(name)
|
||||
|
||||
all_jails, _source_files = await run_blocking(parse_jails_sync, Path(config_dir))
|
||||
all_jails, _source_files = await run_blocking(config_file_service._parse_jails_sync, Path(config_dir))
|
||||
|
||||
if name not in all_jails:
|
||||
raise JailNotFoundInConfigError(name)
|
||||
|
||||
active_names = await get_active_jail_names(socket_path)
|
||||
active_names = await config_file_service._get_active_jail_names(socket_path)
|
||||
if name in active_names:
|
||||
raise JailAlreadyActiveError(name)
|
||||
|
||||
# ---------------------------------------------------------------------- #
|
||||
# Pre-activation validation — collect warnings but do not block #
|
||||
# ---------------------------------------------------------------------- #
|
||||
validation_result: JailValidationResult = await run_blocking(validate_jail_config_sync, Path(config_dir), name
|
||||
validation_result: JailValidationResult = await run_blocking(config_file_service._validate_jail_config_sync, Path(config_dir), name
|
||||
)
|
||||
warnings: list[str] = [f"{i.field}: {i.message}" for i in validation_result.issues]
|
||||
if warnings:
|
||||
@@ -421,7 +395,7 @@ async def _activate_jail(
|
||||
# Activation reload — if it fails, roll back immediately #
|
||||
# ---------------------------------------------------------------------- #
|
||||
try:
|
||||
await reload_all(socket_path, include_jails=[name])
|
||||
await config_file_service.jail_service.reload_all(socket_path, include_jails=[name])
|
||||
except JailNotFoundError as exc:
|
||||
# Jail configuration is invalid (e.g. missing logpath that prevents
|
||||
# fail2ban from loading the jail). Roll back and provide a specific error.
|
||||
@@ -467,7 +441,7 @@ async def _activate_jail(
|
||||
for attempt in range(_POST_RELOAD_MAX_ATTEMPTS):
|
||||
if attempt > 0:
|
||||
await asyncio.sleep(_POST_RELOAD_PROBE_INTERVAL)
|
||||
if await _probe_fail2ban_running(socket_path):
|
||||
if await config_file_service._probe_fail2ban_running(socket_path):
|
||||
fail2ban_running = True
|
||||
break
|
||||
|
||||
@@ -492,7 +466,7 @@ async def _activate_jail(
|
||||
)
|
||||
|
||||
# Verify the jail actually started (config error may prevent it silently).
|
||||
post_reload_names = await get_active_jail_names(socket_path)
|
||||
post_reload_names = await config_file_service._get_active_jail_names(socket_path)
|
||||
actually_running = name in post_reload_names
|
||||
if not actually_running:
|
||||
log.warning(
|
||||
@@ -563,7 +537,7 @@ async def _rollback_activation_async(
|
||||
|
||||
# Step 2 — reload fail2ban with the restored config.
|
||||
try:
|
||||
await reload_all(socket_path)
|
||||
await config_file_service.jail_service.reload_all(socket_path)
|
||||
log.info("jail_activation_rollback_reload_ok", jail=name)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("jail_activation_rollback_reload_failed", jail=name, error=str(exc))
|
||||
@@ -573,7 +547,7 @@ async def _rollback_activation_async(
|
||||
for attempt in range(_POST_RELOAD_MAX_ATTEMPTS):
|
||||
if attempt > 0:
|
||||
await asyncio.sleep(_POST_RELOAD_PROBE_INTERVAL)
|
||||
if await _probe_fail2ban_running(socket_path):
|
||||
if await config_file_service._probe_fail2ban_running(socket_path):
|
||||
log.info("jail_activation_rollback_recovered", jail=name)
|
||||
return True
|
||||
|
||||
@@ -625,14 +599,14 @@ async def _deactivate_jail(
|
||||
~app.utils.fail2ban_client.Fail2BanConnectionError: If the fail2ban
|
||||
socket is unreachable during reload.
|
||||
"""
|
||||
safe_jail_name(name)
|
||||
config_file_service.safe_jail_name(name)
|
||||
|
||||
all_jails, _source_files = await run_blocking(parse_jails_sync, Path(config_dir))
|
||||
all_jails, _source_files = await run_blocking(config_file_service._parse_jails_sync, Path(config_dir))
|
||||
|
||||
if name not in all_jails:
|
||||
raise JailNotFoundInConfigError(name)
|
||||
|
||||
active_names = await get_active_jail_names(socket_path)
|
||||
active_names = await config_file_service._get_active_jail_names(socket_path)
|
||||
if name not in active_names:
|
||||
raise JailAlreadyInactiveError(name)
|
||||
|
||||
@@ -644,7 +618,7 @@ async def _deactivate_jail(
|
||||
)
|
||||
|
||||
try:
|
||||
await reload_all(socket_path, exclude_jails=[name])
|
||||
await config_file_service.jail_service.reload_all(socket_path, exclude_jails=[name])
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("reload_after_deactivate_failed", jail=name, error=str(exc))
|
||||
|
||||
@@ -680,14 +654,14 @@ async def delete_jail_local_override(
|
||||
delete the live config file).
|
||||
ConfigWriteError: If the file cannot be deleted.
|
||||
"""
|
||||
safe_jail_name(name)
|
||||
config_file_service.safe_jail_name(name)
|
||||
|
||||
all_jails, _source_files = await run_blocking(parse_jails_sync, Path(config_dir))
|
||||
all_jails, _source_files = await run_blocking(config_file_service._parse_jails_sync, Path(config_dir))
|
||||
|
||||
if name not in all_jails:
|
||||
raise JailNotFoundInConfigError(name)
|
||||
|
||||
active_names = await get_active_jail_names(socket_path)
|
||||
active_names = await config_file_service._get_active_jail_names(socket_path)
|
||||
if name in active_names:
|
||||
raise JailAlreadyActiveError(name)
|
||||
|
||||
@@ -720,8 +694,8 @@ async def validate_jail_config(
|
||||
Raises:
|
||||
JailNameError: If *name* contains invalid characters.
|
||||
"""
|
||||
safe_jail_name(name)
|
||||
return await run_blocking(validate_jail_config_sync,
|
||||
config_file_service.safe_jail_name(name)
|
||||
return await run_blocking(config_file_service._validate_jail_config_sync,
|
||||
Path(config_dir),
|
||||
name,
|
||||
)
|
||||
@@ -770,7 +744,7 @@ async def _rollback_jail(
|
||||
JailNameError: If *name* contains invalid characters.
|
||||
ConfigWriteError: If writing the ``.local`` file fails.
|
||||
"""
|
||||
safe_jail_name(name)
|
||||
config_file_service.safe_jail_name(name)
|
||||
|
||||
|
||||
# Write enabled=false — this must succeed even when fail2ban is down.
|
||||
@@ -783,15 +757,15 @@ async def _rollback_jail(
|
||||
log.info("jail_rolled_back_disabled", jail=name)
|
||||
|
||||
# Attempt to start the daemon.
|
||||
started = await start_daemon(start_cmd_parts)
|
||||
started = await config_file_service.start_daemon(start_cmd_parts)
|
||||
log.info("jail_rollback_start_attempted", jail=name, start_ok=started)
|
||||
|
||||
# Wait for the socket to come back.
|
||||
fail2ban_running = await wait_for_fail2ban(socket_path, max_wait_seconds=10.0, poll_interval=2.0)
|
||||
fail2ban_running = await config_file_service.wait_for_fail2ban(socket_path, max_wait_seconds=10.0, poll_interval=2.0)
|
||||
|
||||
active_jails = 0
|
||||
if fail2ban_running:
|
||||
names = await get_active_jail_names(socket_path)
|
||||
names = await config_file_service._get_active_jail_names(socket_path)
|
||||
active_jails = len(names)
|
||||
|
||||
if fail2ban_running:
|
||||
|
||||
Reference in New Issue
Block a user