84 lines
2.4 KiB
Python
84 lines
2.4 KiB
Python
"""
|
|
Database Cleanup Manager für sicheres Database-Management.
|
|
Zentrale Verwaltung von Database-Connections und Cleanup-Operationen.
|
|
"""
|
|
|
|
import logging
|
|
from typing import Optional, List
|
|
from contextlib import contextmanager
|
|
import threading
|
|
import weakref
|
|
|
|
from utils.logging_config import get_logger
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
class DatabaseCleanupManager:
|
|
"""
|
|
Manager für sichere Database-Cleanup-Operationen.
|
|
Verwaltet Database-Engines und sorgt für sauberes Shutdown.
|
|
"""
|
|
|
|
def __init__(self):
|
|
self._engines = weakref.WeakSet()
|
|
self._lock = threading.Lock()
|
|
logger.debug("DatabaseCleanupManager initialisiert")
|
|
|
|
def register_engine(self, engine):
|
|
"""
|
|
Registriert eine Database-Engine für Cleanup beim Shutdown.
|
|
|
|
Args:
|
|
engine: SQLAlchemy Engine-Objekt
|
|
"""
|
|
with self._lock:
|
|
self._engines.add(engine)
|
|
logger.debug(f"Database-Engine registriert: {engine}")
|
|
|
|
def cleanup_all(self):
|
|
"""
|
|
Führt Cleanup für alle registrierten Engines durch.
|
|
"""
|
|
with self._lock:
|
|
for engine in list(self._engines):
|
|
try:
|
|
if hasattr(engine, 'dispose'):
|
|
engine.dispose()
|
|
logger.debug(f"Engine disposed: {engine}")
|
|
except Exception as e:
|
|
logger.error(f"Fehler beim Engine-Cleanup: {e}")
|
|
|
|
# Set leeren
|
|
self._engines.clear()
|
|
logger.info("Database-Cleanup abgeschlossen")
|
|
|
|
def get_engine_count(self) -> int:
|
|
"""
|
|
Gibt die Anzahl der registrierten Engines zurück.
|
|
"""
|
|
with self._lock:
|
|
return len(self._engines)
|
|
|
|
|
|
# Globaler Cleanup-Manager
|
|
_cleanup_manager = None
|
|
_manager_lock = threading.Lock()
|
|
|
|
|
|
def get_cleanup_manager() -> DatabaseCleanupManager:
|
|
"""
|
|
Gibt den globalen DatabaseCleanupManager zurück (Singleton).
|
|
|
|
Returns:
|
|
DatabaseCleanupManager: Der globale Cleanup-Manager
|
|
"""
|
|
global _cleanup_manager
|
|
|
|
if _cleanup_manager is None:
|
|
with _manager_lock:
|
|
if _cleanup_manager is None:
|
|
_cleanup_manager = DatabaseCleanupManager()
|
|
logger.debug("Globaler DatabaseCleanupManager erstellt")
|
|
|
|
return _cleanup_manager |