""" Signals for monitoring system """ import logging from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django.utils import timezone from monitoring.models import Alert, SystemStatus from monitoring.services.alerting import AlertingService logger = logging.getLogger(__name__) @receiver(post_save, sender=Alert) def alert_created_handler(sender, instance, created, **kwargs): """Handle alert creation""" if created: logger.info(f"New alert created: {instance.title} ({instance.severity})") # Send notifications for new alerts try: alerting_service = AlertingService() alert_data = { 'rule_id': str(instance.rule.id), 'title': instance.title, 'description': instance.description, 'severity': instance.severity, 'current_value': float(instance.triggered_value) if instance.triggered_value else None, 'threshold_value': float(instance.threshold_value) if instance.threshold_value else None } notification_results = alerting_service.notification_service.send_alert_notifications(alert_data) logger.info(f"Alert notifications sent: {notification_results}") except Exception as e: logger.error(f"Failed to send alert notifications: {e}") @receiver(post_save, sender=SystemStatus) def system_status_changed_handler(sender, instance, created, **kwargs): """Handle system status changes""" if created or instance.tracker.has_changed('status'): logger.info(f"System status changed to: {instance.status}") # Update system status in cache or external systems try: # This could trigger notifications to external systems # or update status pages pass except Exception as e: logger.error(f"Failed to update system status: {e}") # Add tracker to SystemStatus model for change detection from django.db import models class SystemStatusTracker: """Track changes to SystemStatus model""" def __init__(self, instance): self.instance = instance self._initial_data = {} if instance.pk: self._initial_data = { 'status': instance.status, 'message': instance.message } def has_changed(self, field): """Check if a field has changed""" if not self.instance.pk: return True return getattr(self.instance, field) != self._initial_data.get(field) # Monkey patch the SystemStatus model to add tracker def add_tracker_to_system_status(): """Add tracker to SystemStatus instances""" original_init = SystemStatus.__init__ def new_init(self, *args, **kwargs): original_init(self, *args, **kwargs) self.tracker = SystemStatusTracker(self) SystemStatus.__init__ = new_init # Call the function to add tracker add_tracker_to_system_status()