nexus-5/core/tasks/monitoring.py
2026-01-26 11:09:40 -05:00

73 lines
2.1 KiB
Python

"""
Celery tasks for monitoring command execution.
"""
import logging
from celery import shared_task
from core.services.events import EventPublisher
from core.services.monitoring.registry import MonitoringCommandRegistry
logger = logging.getLogger(__name__)
@shared_task(bind=True, max_retries=3, default_retry_delay=300)
def run_monitoring_command(self, command_name: str, **kwargs):
"""
Execute a monitoring command and publish its results as an audit event.
Email delivery happens inside the command's execute() method.
Event publishing creates an audit trail of command executions.
Args:
command_name: Name of the registered monitoring command
**kwargs: Arguments passed to the command
Returns:
Dict with execution summary
"""
try:
# Execute the command (email delivery happens here)
result = MonitoringCommandRegistry.execute(command_name, **kwargs)
# Publish event for audit trail
EventPublisher.publish_sync(
event_type=result.event_type,
entity_type="MonitoringCommand",
entity_id=result.entity_id,
triggered_by=None, # System-generated
metadata={
'command_name': result.command_name,
'execution_date': str(result.execution_date),
'emails_sent': result.emails_sent,
'summary': result.summary,
}
)
logger.info(
f"Monitoring command '{command_name}' executed successfully",
extra={
'command_name': command_name,
'summary': result.summary,
}
)
return {
'status': 'success',
'command': command_name,
'summary': result.summary,
}
except ValueError as e:
# Command not found
logger.error(f"Monitoring command not found: {command_name}")
return {
'status': 'error',
'command': command_name,
'error': str(e),
}
except Exception as exc:
logger.exception(f"Monitoring command '{command_name}' failed")
raise self.retry(exc=exc)