File indexing completed on 2026-04-25 08:29:10
0001 import logging
0002 import atexit
0003 import sys
0004 from django.apps import AppConfig
0005 from django.conf import settings
0006
0007 logger = logging.getLogger(__name__)
0008
0009 class MonitorAppConfig(AppConfig):
0010 """
0011 Django app configuration for monitor_app.
0012 Automatically starts ActiveMQ integration when Django starts.
0013 """
0014 default_auto_field = 'django.db.models.BigAutoField'
0015 name = 'monitor_app'
0016
0017 def ready(self):
0018 """
0019 Called when Django has finished loading all apps.
0020 Initialize ActiveMQ connection if appropriate.
0021 """
0022 if self._should_connect_activemq():
0023 self._initialize_activemq()
0024
0025 def _should_connect_activemq(self):
0026 """
0027 Determine if we should start the ActiveMQ connection.
0028 Only the production WSGI process should subscribe — not runserver,
0029 management commands, or other dev instances. This prevents duplicate
0030 message processing when multiple Django processes share the same DB.
0031 """
0032
0033 if 'mod_wsgi' not in sys.modules:
0034 context = sys.argv[1] if len(sys.argv) > 1 else 'unknown'
0035 logger.info(f"ActiveMQ: skipping (not WSGI, context={context})")
0036 return False
0037
0038 if not getattr(settings, 'ACTIVEMQ_HOST', None):
0039 logger.info("ActiveMQ not configured - listener will not start")
0040 return False
0041
0042 return True
0043
0044 def _initialize_activemq(self):
0045 """Initialize ActiveMQ connection and register cleanup handlers"""
0046 try:
0047 from .activemq_connection import ActiveMQConnectionManager
0048
0049
0050 manager = ActiveMQConnectionManager()
0051
0052
0053 if manager.connect():
0054
0055 atexit.register(self._cleanup_activemq, manager)
0056 logger.info("ActiveMQ integration initialized successfully")
0057 else:
0058 logger.warning("Failed to initialize ActiveMQ connection")
0059
0060 except ImportError as e:
0061 logger.error(f"Could not import ActiveMQ components: {e}")
0062 except Exception as e:
0063 logger.error(f"Failed to initialize ActiveMQ integration: {e}")
0064
0065 def _cleanup_activemq(self, manager):
0066 """Clean up ActiveMQ connection on Django shutdown"""
0067 try:
0068 logger.info("Shutting down ActiveMQ integration...")
0069 manager.disconnect()
0070 except Exception as e:
0071 logger.error(f"Error during ActiveMQ cleanup: {e}")