Kaynağa Gözat

feat: implement graceful shutdown for application and notification monitor

Manuel 1 yıl önce
ebeveyn
işleme
215866a25e
3 değiştirilmiş dosya ile 96 ekleme ve 23 silme
  1. 61 4
      app.py
  2. 12 3
      routes/stats_routes.py
  3. 23 16
      services/notifications.py

+ 61 - 4
app.py

@@ -1,4 +1,8 @@
+import atexit
 import os
+import signal
+import sys
+import threading
 from datetime import datetime
 
 from dotenv import load_dotenv
@@ -18,12 +22,16 @@ from services.notifications import (
     set_commit_notifications,
     set_socketio_instance,
     start_notification_monitor,
+    stop_notification_monitor,
 )
 from utils.filters import register_filters
 
 # Load environment variables
 load_dotenv()
 
+# Global shutdown event
+shutdown_event = threading.Event()
+
 
 def create_app():
     # Run database migration at startup
@@ -120,6 +128,35 @@ def setup_scheduler_tasks(scheduler):
             logger.error(f"Error in metrics cleanup task: {e}")
 
 
+def shutdown_app(scheduler, socketio):
+    logger.info("\n🛑 Shutting down SquidStats...")
+    
+    # Set shutdown event to stop all threads
+    shutdown_event.set()
+    
+    # Stop notification monitor
+    logger.info("Stopping notification monitor...")
+    stop_notification_monitor()
+    
+    # Stop scheduler
+    logger.info("Stopping scheduler...")
+    try:
+        if scheduler and scheduler.running:
+            scheduler.shutdown(wait=False)
+    except Exception as e:
+        logger.error(f"Error stopping scheduler: {e}")
+    
+    # Stop SocketIO
+    logger.info("Stopping SocketIO...")
+    try:
+        if socketio:
+            socketio.stop()
+    except Exception as e:
+        logger.error(f"Error stopping SocketIO: {e}")
+    
+    logger.info("✅ Shutdown complete")
+
+
 def main():
     # Create Flask app and scheduler
     app, scheduler = create_app()
@@ -137,7 +174,19 @@ def main():
     start_notification_monitor()
 
     # Start real-time data collection thread
-    socketio.start_background_task(realtime_data_thread, socketio)
+    socketio.start_background_task(realtime_data_thread, socketio, shutdown_event)
+
+    # Register signal handlers for graceful shutdown
+    def signal_handler(signum, frame):
+        logger.info(f"\n⚠️ Received signal {signum}")
+        shutdown_app(scheduler, socketio)
+        sys.exit(0)
+    
+    signal.signal(signal.SIGINT, signal_handler)  # Ctrl+C
+    signal.signal(signal.SIGTERM, signal_handler)  # kill command
+    
+    # Register cleanup on exit
+    atexit.register(lambda: shutdown_app(scheduler, socketio))
 
     # Run the application
     debug_mode = Config.DEBUG
@@ -154,9 +203,17 @@ def main():
         logger.warning(f"Invalid PORT value '{port_str}', falling back to 5000")
         port = 5000
 
-    socketio.run(
-        app, debug=debug_mode, host=host, port=port, allow_unsafe_werkzeug=True
-    )
+    try:
+        socketio.run(
+            app, debug=debug_mode, host=host, port=port, allow_unsafe_werkzeug=True
+        )
+    except KeyboardInterrupt:
+        logger.info("\n⚠️ Keyboard interrupt received")
+        shutdown_app(scheduler, socketio)
+    except Exception as e:
+        logger.error(f"Application error: {e}")
+        shutdown_app(scheduler, socketio)
+        raise
 
 
 if __name__ == "__main__":

+ 12 - 3
routes/stats_routes.py

@@ -84,13 +84,15 @@ def print_icap_service():
     return jsonify(result), status """
 
 
-def realtime_data_thread(socketio):
+def realtime_data_thread(socketio, shutdown_event=None):
     global realtime_cache_stats, realtime_system_info
     import time
 
     data_collection_counter = 0
 
-    while True:
+    logger.info("Real-time data collection thread started")
+    
+    while not (shutdown_event and shutdown_event.is_set()):
         try:
             cache_data = fetch_squid_cache_stats()
             cache_stats = (
@@ -191,4 +193,11 @@ def realtime_data_thread(socketio):
             )
         except Exception as e:
             logger.error(f"Error in real-time data thread: {str(e)}")
-        time.sleep(15)  # Actualizar cada 15 segundos
+        
+        # Use wait with timeout for responsive shutdown
+        if shutdown_event:
+            shutdown_event.wait(timeout=15)
+        else:
+            time.sleep(15)
+    
+    logger.info("Real-time data collection thread stopped")

+ 23 - 16
services/notifications.py

@@ -12,12 +12,27 @@ from database.database import Notification, get_session
 # Global variable for Socket.IO
 socketio = None
 
+# Global stop event for notification monitor
+_monitor_stop_event = None
+_monitor_thread = None
+
 
 def set_socketio_instance(sio):
     global socketio
     socketio = sio
 
 
+def stop_notification_monitor():
+    """Stop the notification monitor thread"""
+    global _monitor_stop_event, _monitor_thread
+    
+    if _monitor_stop_event:
+        _monitor_stop_event.set()
+    
+    if _monitor_thread and _monitor_thread.is_alive():
+        _monitor_thread.join(timeout=5)
+
+
 def _generate_message_hash(message: str, source: str, notification_type: str) -> str:
     """Generate SHA256 hash for deduplication"""
     content = f"{source}:{notification_type}:{message}"
@@ -452,23 +467,15 @@ def has_remote_commits_with_messages(
 # Thread for periodic checks
 def start_notification_monitor():
     """Starts the notification monitor in background with graceful shutdown support"""
-    import signal
-
-    stop_event = threading.Event()
-
-    def signal_handler(signum, frame):
-        """Handle shutdown signals gracefully"""
-        stop_event.set()
-
-    # Register signal handlers for graceful shutdown
-    signal.signal(signal.SIGTERM, signal_handler)
-    signal.signal(signal.SIGINT, signal_handler)
+    global _monitor_stop_event, _monitor_thread
+    
+    _monitor_stop_event = threading.Event()
 
     def monitor_loop():
         check_count = 0
         cycle_interval = 60  # 1 minute between cycles for better granularity
 
-        while not stop_event.is_set():
+        while not _monitor_stop_event.is_set():
             try:
                 # Check commits every 30 minutes (every 30 cycles)
                 if check_count % 30 == 0:
@@ -499,14 +506,14 @@ def start_notification_monitor():
             except Exception as e:
                 print(f"Error in notification monitor: {e}")
 
-            stop_event.wait(timeout=cycle_interval)
+            _monitor_stop_event.wait(timeout=cycle_interval)
 
-    thread = threading.Thread(
+    _monitor_thread = threading.Thread(
         target=monitor_loop, daemon=True, name="NotificationMonitor"
     )
-    thread.start()
+    _monitor_thread.start()
 
-    return stop_event  # Return the event for potential external control
+    return _monitor_stop_event  # Return the event for potential external control
 
 
 # Specific functions for Squid that can be called from other parts