Skip to content

Home Information - Your home, your data, organized.

Python

[Bug] Fix ZoneMinder integration stops working - Phase 1 Enhanced Monitoring (#206)

Tony C90b27d73a6ca
diff --git a/.claude/commands/execute.md b/.claude/commands/execute.md
index 4b9a6154..f6edbfa0 100644
--- a/.claude/commands/execute.md
+++ b/.claude/commands/execute.md
@@ -104,12 +104,16 @@ Execute complete strategic-to-delivery workflow with intelligent coordination:
- Architecture and patterns aligned
- Documentation updated appropriately
+ **Code Review:**
+ - Use `/review` command for self-review before PR creation
+ - This ensures all changes meet project standards
+
8. **Phase 6: PR Creation** - Automated pull request generation:
- - Generate PR title based on issue and implementation
- - Create comprehensive PR description following template
- - Use file-based approach for GitHub CLI: write PR body to temp file, then `gh pr create --body-file`
- - Include proper issue linking: `Closes #$1`
- - Select appropriate category and fill testing section
+ - Use `/commit` command to create a properly formatted commit with issue context
+ - Use `/pr` command to create pull request with standard template
+ - This ensures consistent formatting and automatic issue linking
+ - The `/pr` command handles `Closes #$1` automatically
+ - Example: `/pr bugfix/205-monitoring 205`
9. **Phase 7: Post-Creation Validation** - Verify successful completion:
- Confirm PR created successfully
diff --git a/Dockerfile b/Dockerfile
index dc08e4ae..de36775c 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -26,7 +26,7 @@ VOLUME /data/database /data/media
RUN mkdir -p /data/database && mkdir -p /data/media
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
- CMD curl -f http://localhost:8000/health/ || exit 1
+ CMD curl -f http://localhost:8000/health || exit 1
# Assumes base.txt is all that is needed (ignores dev-specific dependencies)
COPY src/hi/requirements/base.txt /src/requirements.txt
diff --git a/src/hi/apps/alert/alert_mixins.py b/src/hi/apps/alert/alert_mixins.py
index 66012168..d37e3f50 100644
--- a/src/hi/apps/alert/alert_mixins.py
+++ b/src/hi/apps/alert/alert_mixins.py
@@ -19,7 +19,7 @@ class AlertMixin:
if not hasattr( self, '_alert_manager' ):
self._alert_manager = AlertManager()
try:
- await asyncio.shield( sync_to_async(self._alert_manager.ensure_initialized )())
+ await asyncio.shield( sync_to_async(self._alert_manager.ensure_initialized, thread_sensitive=True )())
except asyncio.CancelledError:
logger.warning( 'AlertMixin sync_to_async() was cancelled! Handling gracefully.' )
diff --git a/src/hi/apps/common/asyncio_utils.py b/src/hi/apps/common/asyncio_utils.py
index 454d7cd3..c70c3e0b 100644
--- a/src/hi/apps/common/asyncio_utils.py
+++ b/src/hi/apps/common/asyncio_utils.py
@@ -1,25 +1,137 @@
import asyncio
+import weakref
+import threading
from threading import Thread
+class BackgroundTaskMonitor:
+ """Monitor for background event loops and tasks running in daemon threads"""
+ _instances = {} # task_function_name -> monitor info
+
+ @classmethod
+ def register_background_task(cls, name, loop, thread):
+ """Register a background task for monitoring"""
+ cls._instances[name] = {
+ 'loop_ref': weakref.ref(loop) if loop else None,
+ 'thread_ref': weakref.ref(thread) if thread else None,
+ 'thread_name': thread.name if thread else None,
+ 'registered_at': threading.current_thread().name,
+ }
+
+ @classmethod
+ def get_background_task_status(cls):
+ """Get comprehensive status of all background tasks and loops"""
+ status = {
+ 'main_thread': {
+ 'name': threading.main_thread().name,
+ 'is_alive': threading.main_thread().is_alive(),
+ },
+ 'current_thread': {
+ 'name': threading.current_thread().name,
+ 'active_count': threading.active_count(),
+ },
+ 'background_tasks': {}
+ }
+
+ for task_name, info in cls._instances.items():
+ task_status = {
+ 'registered_from': info.get('registered_at'),
+ 'thread_name': info.get('thread_name'),
+ }
+
+ # Check thread status
+ thread = info['thread_ref']() if info['thread_ref'] else None
+ task_status['thread'] = {
+ 'exists': thread is not None,
+ 'is_alive': thread.is_alive() if thread else False,
+ 'is_daemon': thread.daemon if thread else None,
+ }
+
+ # Check event loop status
+ loop = info['loop_ref']() if info['loop_ref'] else None
+ if loop:
+ try:
+ # Get tasks from the background loop
+ tasks = asyncio.all_tasks(loop)
+ task_details = []
+
+ for task in tasks:
+ try:
+ task_info = {
+ 'name': getattr(task, 'get_name', lambda: 'unnamed')(),
+ 'done': task.done(),
+ 'cancelled': task.cancelled(),
+ }
+
+ # Try to get coroutine name safely
+ try:
+ coro = task.get_coro()
+ if hasattr(coro, '__name__'):
+ task_info['coro_name'] = coro.__name__
+ elif hasattr(coro, '__qualname__'):
+ task_info['coro_name'] = coro.__qualname__
+ else:
+ task_info['coro_name'] = str(type(coro).__name__)
+ except Exception:
+ task_info['coro_name'] = 'unknown'
+
+ task_details.append(task_info)
+ except Exception as e:
+ task_details.append({'error': f'Task info error: {e}'})
+
+ task_status['event_loop'] = {
+ 'exists': True,
+ 'is_running': loop.is_running(),
+ 'is_closed': loop.is_closed(),
+ 'total_tasks': len(tasks),
+ 'active_tasks': len([t for t in tasks if not t.done()]),
+ 'task_details': task_details,
+ }
+ except Exception as e:
+ task_status['event_loop'] = {
+ 'exists': True,
+ 'error': f'Loop access error: {e}'
+ }
+ else:
+ task_status['event_loop'] = {
+ 'exists': False,
+ 'error': 'Event loop reference is dead'
+ }
+
+ status['background_tasks'][task_name] = task_status
+
+ return status
+
+
def start_background_event_loop( task_function, pass_event_loop = False ):
"""
Generic function to start a background thread running an async task.
-
+
:param task_function: Async function to be executed inside the thread.
"""
- def run_background_task_in_thread():
+ # Generate a name for this background task
+ task_name = getattr(task_function, '__name__', str(task_function))
+ if hasattr(task_function, '__self__'):
+ # This is a method, include the class name
+ class_name = task_function.__self__.__class__.__name__
+ task_name = f"{class_name}.{task_name}"
+ def run_background_task_in_thread():
background_loop = asyncio.new_event_loop()
asyncio.set_event_loop( background_loop )
-
+
+ # Register this task for monitoring
+ current_thread = threading.current_thread()
+ current_thread.name = f"Background-{task_name}"
+ BackgroundTaskMonitor.register_background_task(task_name, background_loop, current_thread)
+
async def run_background_task():
if pass_event_loop:
await task_function( background_loop )
else:
await task_function()
return
-
+
background_loop.call_soon_threadsafe( asyncio.create_task, run_background_task() )
background_loop.run_forever()
return
diff --git a/src/hi/apps/common/singleton_manager.py b/src/hi/apps/common/singleton_manager.py
new file mode 100644
index 00000000..801b5219
--- /dev/null
+++ b/src/hi/apps/common/singleton_manager.py
@@ -0,0 +1,78 @@
+"""
+Base class for singleton managers with async-safe initialization patterns.
+"""
+
+import asyncio
+import logging
+from abc import abstractmethod
+from threading import Lock
+
+from asgiref.sync import sync_to_async
+from .singleton import Singleton
+
+logger = logging.getLogger(__name__)
+
+
+class SingletonManager(Singleton):
+ """
+ Base class for singleton managers that need both sync and async initialization.
+
+ Provides thread-safe and async-safe initialization patterns with:
+ - ensure_initialized() for sync contexts
+ - ensure_initialized_async() for async contexts
+ - reload() for sync reload (with threading.Lock)
+ - reload_async() for async reload (with asyncio.Lock)
+
+ Subclasses must implement:
+ - _reload_implementation(): The actual reload logic (called with locks held)
+ """
+
+ def __init_singleton__(self):
+ super().__init_singleton__()
+ self._was_initialized = False
+ self._data_lock = Lock() # For sync contexts
+ self._async_data_lock = asyncio.Lock() # For async contexts
+
+ @abstractmethod
+ def _reload_implementation(self):
+ """
+ Perform the actual manager initialization/reload work.
+ Called with appropriate locks already held.
+ """
+ pass
+
+ def reload(self):
+ """Reload manager configuration in sync context."""
+ logger.debug(f'{self.__class__.__name__} loading started.')
+ with self._data_lock:
+ self._reload_implementation()
+ logger.debug(f'{self.__class__.__name__} loading completed.')
+
+ async def reload_async(self):
+ """Reload manager configuration in async context."""
+ logger.debug(f'{self.__class__.__name__} loading started (async).')
+ async with self._async_data_lock:
+ # Use sync_to_async for Django ORM operations in _reload_implementation
+ await sync_to_async(self._reload_implementation, thread_sensitive=True)()
+ logger.debug(f'{self.__class__.__name__} loading completed (async).')
+
+ def ensure_initialized(self):
+ """Thread-safe initialization for synchronous contexts."""
+ if self._was_initialized:
+ return
+ with self._data_lock:
+ # Double-check pattern
+ if not self._was_initialized:
+ self._reload_implementation()
+ self._was_initialized = True
+
+ async def ensure_initialized_async(self):
+ """Async-safe initialization for asynchronous contexts."""
+ if self._was_initialized:
+ return
+ async with self._async_data_lock:
+ # Double-check pattern
+ if not self._was_initialized:
+ await sync_to_async(self._reload_implementation, thread_sensitive=True)()
+ self._was_initialized = True
+
diff --git a/src/hi/apps/event/event_manager.py b/src/hi/apps/event/event_manager.py
index 28bec797..5f2fb01f 100644
--- a/src/hi/apps/event/event_manager.py
+++ b/src/hi/apps/event/event_manager.py
@@ -76,28 +76,29 @@ class EventManager( Singleton, AlertMixin, ControllerMixin, SecurityMixin ):
entity_state_transition_list : List[ EntityStateTransition ] ):
if not entity_state_transition_list:
return
+
logger.debug( f'Adding state transitions: {entity_state_transition_list}' )
self._recent_transitions.extend( entity_state_transition_list )
self._purge_old_transitions()
- new_event_list = await self._get_new_events()
-
+ new_event_list = await sync_to_async(self._get_new_events, thread_sensitive=True)()
logger.debug( f'New events found: {new_event_list}' )
await self._do_new_event_action( event_list = new_event_list )
- await self._add_to_event_history( event_list = new_event_list )
+ await self._add_to_event_history( event_list = new_event_list )
+
return
- async def _get_new_events( self ):
+ def _get_new_events( self ):
if self._event_definition_reload_needed:
- await sync_to_async( self.reload, thread_sensitive = True )()
-
+ self.reload()
+
with self._event_definitions_lock:
new_event_list = list()
for event_definition in self._event_definitions:
- if await self._has_recent_event( event_definition ):
+ if self._has_recent_event( event_definition ):
continue
- event = await self._create_event_if_detected( event_definition )
+ event = self._create_event_if_detected( event_definition )
if not event:
continue
self._recent_events[event_definition.id] = event
@@ -106,21 +107,21 @@ class EventManager( Singleton, AlertMixin, ControllerMixin, SecurityMixin ):
return new_event_list
- async def _has_recent_event( self, event_definition : EventDefinition ) -> bool:
+ def _has_recent_event( self, event_definition : EventDefinition ) -> bool:
recent_event = self._recent_events.get( event_definition.id )
if not recent_event:
return False
recent_event_timedelta = datetimeproxy.now() - recent_event.timestamp
return bool( recent_event_timedelta.total_seconds() <= event_definition.dedupe_window_secs )
- async def _create_event_if_detected( self, event_definition : EventDefinition ) -> bool:
- if not await sync_to_async(event_definition.event_clauses.exists)():
+ def _create_event_if_detected( self, event_definition : EventDefinition ) -> bool:
+ if not event_definition.event_clauses.exists():
return False
current_timestamp = datetimeproxy.now()
sensor_response_list = list()
-
- event_clauses = await sync_to_async(list)(event_definition.event_clauses.select_related('entity_state').all())
+
+ event_clauses = list(event_definition.event_clauses.select_related('entity_state').all())
for event_clause in event_clauses:
matches = False
for transition in self._recent_transitions:
@@ -137,7 +138,7 @@ class EventManager( Singleton, AlertMixin, ControllerMixin, SecurityMixin ):
if not matches:
return False
continue
-
+
return Event(
event_definition = event_definition,
sensor_response_list = sensor_response_list,
diff --git a/src/hi/apps/event/tests/test_event_manager.py b/src/hi/apps/event/tests/test_event_manager.py
index 9b333595..e21a93e6 100644
--- a/src/hi/apps/event/tests/test_event_manager.py
+++ b/src/hi/apps/event/tests/test_event_manager.py
@@ -311,7 +311,7 @@ class TestEventManagerEventDetection(AsyncEventManagerTestCase):
self.manager._recent_transitions.append(transition)
# Should detect event
- event = await self.manager._create_event_if_detected(event_def)
+ event = await sync_to_async(self.manager._create_event_if_detected)(event_def)
self.assertIsInstance(event, Event)
self.assertEqual(event.event_definition, event_def)
@@ -381,7 +381,7 @@ class TestEventManagerEventDetection(AsyncEventManagerTestCase):
self.manager._recent_transitions.extend([transition1, transition2])
# Should detect event with both sensor responses
- event = await self.manager._create_event_if_detected(event_def)
+ event = await sync_to_async(self.manager._create_event_if_detected)(event_def)
self.assertIsInstance(event, Event)
self.assertEqual(len(event.sensor_response_list), 2)
@@ -431,7 +431,7 @@ class TestEventManagerEventDetection(AsyncEventManagerTestCase):
manager._recent_transitions.append(transition)
# Should NOT detect event due to timing constraint
- event = await manager._create_event_if_detected(event_def)
+ event = await sync_to_async(manager._create_event_if_detected)(event_def)
self.assertFalse(event)
@@ -457,7 +457,7 @@ class TestEventManagerDeduplication(AsyncEventManagerTestCase):
self.manager._recent_events[event_def.id] = recent_event
# Should detect recent event within dedupe window
- has_recent = await self.manager._has_recent_event(event_def)
+ has_recent = self.manager._has_recent_event(event_def)
self.assertTrue(has_recent)
@@ -483,7 +483,7 @@ class TestEventManagerDeduplication(AsyncEventManagerTestCase):
self.manager._recent_events[event_def.id] = old_event
# Should NOT have recent event (outside dedupe window)
- has_recent = await self.manager._has_recent_event(event_def)
+ has_recent = self.manager._has_recent_event(event_def)
self.assertFalse(has_recent)
diff --git a/src/hi/apps/monitor/periodic_monitor.py b/src/hi/apps/monitor/periodic_monitor.py
index afa5d319..352f5d01 100644
--- a/src/hi/apps/monitor/periodic_monitor.py
+++ b/src/hi/apps/monitor/periodic_monitor.py
@@ -27,18 +27,34 @@ class PeriodicMonitor:
async def start(self) -> None:
self._is_running = True
- await self.initialize()
- self._logger.info(f"{self.__class__.__name__} started.")
+ self._logger.info(f"{self.__class__.__name__} async task starting (interval: {self._query_interval_secs}s)")
+
try:
+ await self.initialize()
+ self._logger.info(f"{self.__class__.__name__} initialized successfully, entering monitoring loop")
+
while self._is_running:
- await self.run_query()
+ try:
+ await self.run_query()
+ except Exception as e:
+ self._logger.exception(f"Query execution failed in {self.__class__.__name__}: {e}")
+ # Continue running despite individual query failures
+
+ # Log sleep phase for debugging hanging issues
+ self._logger.debug(f"{self.__class__.__name__} sleeping for {self._query_interval_secs}s")
await asyncio.sleep(self._query_interval_secs)
-
+ self._logger.debug(f"{self.__class__.__name__} woke up, checking if still running: {self._is_running}")
+
except asyncio.CancelledError as ce:
- self._logger.exception( 'Monitor cancelled' )
- self._logger.info(f"{self.__class__.__name__} stopped. ({ce})")
+ self._logger.info(f"{self.__class__.__name__} async task cancelled: {ce}")
+ raise # Re-raise to properly handle cancellation
+ except Exception as e:
+ self._logger.exception(f"{self.__class__.__name__} async task failed unexpectedly: {e}")
+ raise
finally:
+ self._logger.info(f"{self.__class__.__name__} async task cleaning up")
await self.cleanup()
+ self._logger.info(f"{self.__class__.__name__} async task stopped")
return
def stop(self) -> None:
@@ -57,10 +73,24 @@ class PeriodicMonitor:
async def run_query(self) -> None:
self._query_counter += 1
self._logger.debug(f"Running query {self._query_counter} for {self.__class__.__name__}")
+
+ import hi.apps.common.datetimeproxy as datetimeproxy
+ query_start_time = datetimeproxy.now()
+
try:
await self.do_work()
+ query_duration = (datetimeproxy.now() - query_start_time).total_seconds()
+ self._logger.debug(f"Query {self._query_counter} completed successfully in {query_duration:.2f}s")
+
+ # Log warning if query is taking too long relative to interval
+ if query_duration > (self._query_interval_secs * 0.5):
+ self._logger.warning(f"Query {self._query_counter} took {query_duration:.2f}s, "
+ f"which is over 50% of the {self._query_interval_secs}s interval")
+
except Exception as e:
- self._logger.exception(f"Error during query execution: {e}")
+ query_duration = (datetimeproxy.now() - query_start_time).total_seconds()
+ self._logger.exception(f"Query {self._query_counter} failed after {query_duration:.2f}s: {e}")
+ # Don't re-raise - the monitor loop in start() will continue despite failures
return
async def do_work(self) -> None:
diff --git a/src/hi/apps/notify/notify_mixins.py b/src/hi/apps/notify/notify_mixins.py
index 3c8aae9e..540814a2 100644
--- a/src/hi/apps/notify/notify_mixins.py
+++ b/src/hi/apps/notify/notify_mixins.py
@@ -19,7 +19,7 @@ class NotificationMixin:
if not hasattr( self, '_notification_manager' ):
self._notification_manager = NotificationManager()
try:
- await asyncio.shield( sync_to_async( self._notification_manager.ensure_initialized )())
+ await asyncio.shield( sync_to_async( self._notification_manager.ensure_initialized, thread_sensitive=True )())
except asyncio.CancelledError:
logger.warning( 'Notification init sync_to_async() was cancelled! Handling gracefully.')
diff --git a/src/hi/apps/sense/sensor_history_manager.py b/src/hi/apps/sense/sensor_history_manager.py
index 4ba929dd..e88952e5 100644
--- a/src/hi/apps/sense/sensor_history_manager.py
+++ b/src/hi/apps/sense/sensor_history_manager.py
@@ -53,6 +53,8 @@ class SensorHistoryManager( Singleton ):
return
async def _bulk_create_sensor_history_async( self, sensor_history_list : List[ SensorHistory ] ):
+ if not sensor_history_list:
+ return
await sync_to_async( SensorHistory.objects.bulk_create,
thread_sensitive = True)( sensor_history_list )
return
diff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.py
index 98d62e1c..89f25b54 100644
--- a/src/hi/apps/sense/sensor_response_manager.py
+++ b/src/hi/apps/sense/sensor_response_manager.py
@@ -30,7 +30,7 @@ class SensorResponseMixin:
if not hasattr( self, '_sensor_response_manager' ):
self._sensor_response_manager = SensorResponseManager()
try:
- await asyncio.shield( sync_to_async( self._sensor_response_manager.ensure_initialized )())
+ await asyncio.shield( sync_to_async( self._sensor_response_manager.ensure_initialized, thread_sensitive=True )())
except asyncio.CancelledError:
logger.warning( 'SensorResponse init sync_to_async() was cancelled! Handling gracefully.')
@@ -113,6 +113,7 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
previous_sensor_response = SensorResponse.from_string( cached_value )
if latest_sensor_response.value == previous_sensor_response.value:
continue
+
entity_state_transition = await self._create_entity_state_transition(
previous_sensor_response = previous_sensor_response,
latest_sensor_response = latest_sensor_response,
@@ -122,13 +123,15 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
changed_sensor_response_list.append( latest_sensor_response )
continue
-
- logger.debug( f'Sensors changed: {len(changed_sensor_response_list)} of {len(sensor_response_map)}' )
+
await self._add_latest_sensor_responses( changed_sensor_response_list )
+
event_manager = await self.event_manager_async()
if not event_manager:
return
+
await event_manager.add_entity_state_transitions( entity_state_transition_list )
+
return
def get_all_latest_sensor_responses( self ) -> Dict[ Sensor, List[ SensorResponse ] ]:
@@ -206,7 +209,9 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
pipeline.execute()
await self._add_sensors( sensor_response_list = sensor_response_list )
+
sensor_history_manager = await self.sensor_history_manager_async()
+
await sensor_history_manager.add_to_sensor_history(
sensor_response_list = sensor_response_list,
)
diff --git a/src/hi/integrations/templates/integrations/modals/integration_health_status.html b/src/hi/integrations/templates/integrations/modals/integration_health_status.html
index c5ff9e3b..6c999041 100644
--- a/src/hi/integrations/templates/integrations/modals/integration_health_status.html
+++ b/src/hi/integrations/templates/integrations/modals/integration_health_status.html
@@ -1,11 +1,13 @@
{% extends "modals/action_done.html" %}
{% load icons %}
+{% load tz %}
{% block title_text %}
{{ integration_data.label }} Health Status
{% endblock %}
{% block body %}
+{% timezone USER_TIMEZONE %}
<div class="mb-3">
<div class="d-flex align-items-center mb-2">
@@ -23,7 +25,7 @@
<div class="row">
<div class="col-sm-3"><strong>Last Check:</strong></div>
- <div class="col-sm-9">{{ health_status.last_check|date:"M j, Y H:i:s" }}</div>
+ <div class="col-sm-9">{{ health_status.last_check|localtime|date:"M j, Y H:i:s" }}</div>
</div>
{% if health_status.error_message %}
@@ -44,6 +46,114 @@
</div>
{% endif %}
+{% if health_status.monitor_heartbeat %}
+<div class="row mt-3">
+ <div class="col-sm-12">
+ <h6 class="mb-2">Enhanced Monitoring</h6>
+ </div>
+ <div class="col-sm-3"><strong>Monitor Status:</strong></div>
+ <div class="col-sm-9">
+ {% if health_status.monitor_heartbeat_age_seconds < 30 %}
+ <span class="text-success">
+ {% icon "check-circle" size="sm" css_class="mr-1" %}Active
+ </span>
+ (last seen {{ health_status.monitor_heartbeat|localtime|date:"H:i:s" }})
+ {% else %}
+ <span class="text-warning">
+ {% icon "warning" size="sm" css_class="mr-1" %}Stale
+ </span>
+ ({{ health_status.monitor_heartbeat_age_seconds|floatformat:0 }} seconds ago)
+ {% endif %}
+ </div>
+</div>
+
+{% if health_status.last_api_success %}
+<div class="row mt-2">
+ <div class="col-sm-3"><strong>Last API Success:</strong></div>
+ <div class="col-sm-9">{{ health_status.last_api_success|localtime|date:"H:i:s" }}</div>
+</div>
+{% endif %}
+
+{% if health_status.api_metrics %}
+<div class="row mt-2">
+ <div class="col-sm-3"><strong>API Metrics:</strong></div>
+ <div class="col-sm-9">
+ <div class="small">
+ <div>Total calls: {{ health_status.api_metrics.total_calls }}</div>
+ {% if health_status.api_metrics.total_failures > 0 %}
+ <div class="text-warning">
+ {% icon "warning" size="sm" css_class="mr-1" %}
+ Failures: {{ health_status.api_metrics.total_failures }}
+ ({{ health_status.api_metrics.consecutive_failures }} consecutive)
+ </div>
+ {% endif %}
+ {% if health_status.api_metrics.last_response_time %}
+ <div>
+ Last response time: {{ health_status.api_metrics.last_response_time|floatformat:2 }}s
+ </div>
+ {% endif %}
+ </div>
+ </div>
+</div>
+{% endif %}
+
+{% if health_status.async_diagnostics %}
+<div class="row mt-2">
+ <div class="col-sm-3"><strong>Background Tasks:</strong></div>
+ <div class="col-sm-9">
+ <div class="small">
+ <div>Main Thread: {{ health_status.async_diagnostics.main_thread.name }}</div>
+ <div>Active Threads: {{ health_status.async_diagnostics.current_thread.active_count }}</div>
+
+ {% for task_name, task_info in health_status.async_diagnostics.background_tasks.items %}
+ <div class="mt-1 p-1 border-left border-info">
+ <div><strong>{{ task_name }}</strong></div>
+ <div>Thread:
+ {% if task_info.thread.is_alive %}
+ <span class="text-success">
+ {% icon "check-circle" size="sm" css_class="mr-1" %}{{ task_info.thread_name }}
+ </span>
+ {% else %}
+ <span class="text-danger">
+ {% icon "warning" size="sm" css_class="mr-1" %}Dead
+ </span>
+ {% endif %}
+ </div>
+ <div>Event Loop:
+ {% if task_info.event_loop.exists and task_info.event_loop.is_running %}
+ <span class="text-success">
+ {% icon "check-circle" size="sm" css_class="mr-1" %}Running ({{ task_info.event_loop.active_tasks }} active tasks)
+ </span>
+ {% elif task_info.event_loop.exists %}
+ <span class="text-warning">
+ {% icon "warning" size="sm" css_class="mr-1" %}Stopped
+ </span>
+ {% else %}
+ <span class="text-danger">
+ {% icon "warning" size="sm" css_class="mr-1" %}Dead
+ </span>
+ {% endif %}
+ </div>
+
+ {% if task_info.event_loop.task_details %}
+ <div class="mt-1">
+ <small>Tasks:</small>
+ {% for task_detail in task_info.event_loop.task_details %}
+ <div class="ml-2 small">
+ - {{ task_detail.coro_name|default:"unknown" }}
+ {% if task_detail.done %}(done){% elif task_detail.cancelled %}(cancelled){% else %}(running){% endif %}
+ </div>
+ {% endfor %}
+ </div>
+ {% endif %}
+ </div>
+ {% endfor %}
+ </div>
+ </div>
+</div>
+{% endif %}
+{% endif %}
+
{% if health_status.is_healthy %}
<div class="alert alert-success mt-3">
<p class="mb-0">
@@ -67,4 +177,5 @@
</div>
{% endif %}
+{% endtimezone %}
{% endblock %}
diff --git a/src/hi/integrations/transient_models.py b/src/hi/integrations/transient_models.py
index 88939c9d..953f1fef 100644
--- a/src/hi/integrations/transient_models.py
+++ b/src/hi/integrations/transient_models.py
@@ -82,6 +82,11 @@ class IntegrationHealthStatus:
last_check : datetime
error_message : Optional[str] = None
error_count : int = 0
+ # Enhanced monitoring fields for debugging transient issues
+ monitor_heartbeat : Optional[datetime] = None # Last time the monitor cycled successfully
+ last_api_success : Optional[datetime] = None # Last successful API call
+ api_metrics : Optional[Dict] = None # API call performance metrics
+ async_diagnostics : Optional[Dict] = None # Background task and async loop diagnostics
@property
def is_healthy(self) -> bool:
@@ -100,7 +105,7 @@ class IntegrationHealthStatus:
return self.status.label
def to_dict(self) -> Dict:
- return {
+ result = {
'status': self.status.value,
'status_display': self.status_display,
'last_check': self.last_check,
@@ -111,6 +116,24 @@ class IntegrationHealthStatus:
'is_critical': self.is_critical,
}
+ # Include enhanced monitoring fields if present
+ if self.monitor_heartbeat is not None:
+ import hi.apps.common.datetimeproxy as datetimeproxy
+ heartbeat_age = (datetimeproxy.now() - self.monitor_heartbeat).total_seconds()
+ result['monitor_heartbeat'] = self.monitor_heartbeat
+ result['monitor_heartbeat_age_seconds'] = heartbeat_age
+
+ if self.last_api_success is not None:
+ result['last_api_success'] = self.last_api_success
+
+ if self.api_metrics is not None:
+ result['api_metrics'] = self.api_metrics
+
+ if self.async_diagnostics is not None:
+ result['async_diagnostics'] = self.async_diagnostics
+
+ return result
+
@dataclass
class IntegrationValidationResult:
diff --git a/src/hi/services/hass/hass_manager.py b/src/hi/services/hass/hass_manager.py
index a7ca90a8..4aef9ef7 100644
--- a/src/hi/services/hass/hass_manager.py
+++ b/src/hi/services/hass/hass_manager.py
@@ -1,10 +1,9 @@
import logging
from asgiref.sync import sync_to_async
-from threading import Lock
from typing import Dict, List
import hi.apps.common.datetimeproxy as datetimeproxy
-from hi.apps.common.singleton import Singleton
+from hi.apps.common.singleton_manager import SingletonManager
from hi.apps.common.utils import str_to_bool
from hi.integrations.exceptions import (
@@ -29,16 +28,15 @@ from .hass_models import HassState
logger = logging.getLogger(__name__)
-class HassManager( Singleton ):
+class HassManager( SingletonManager ):
def __init_singleton__( self ):
+ super().__init_singleton__()
self._hass_attr_type_to_attribute = dict()
self._hass_client = None
self._client_factory = HassClientFactory()
self._change_listeners = set()
- self._was_initialized = False
- self._data_lock = Lock()
# Health status tracking
self._health_status = IntegrationHealthStatus(
@@ -46,13 +44,6 @@ class HassManager( Singleton ):
last_check=datetimeproxy.now()
)
return
-
- def ensure_initialized(self):
- if self._was_initialized:
- return
- self.reload()
- self._was_initialized = True
- return
def register_change_listener( self, callback ):
if callback not in self._change_listeners:
@@ -71,40 +62,40 @@ class HassManager( Singleton ):
logger.exception( 'Problem calling setting change callback.' )
continue
return
-
+
@property
def hass_client(self):
return self._hass_client
-
- def reload( self ):
- """ Called when integration models are changed (via signals below). """
- logger.debug( 'HASS manager loading started.' )
- with self._data_lock:
- try:
- self._hass_attr_type_to_attribute = self._load_attributes()
- self._hass_client = self.create_hass_client( self._hass_attr_type_to_attribute )
- self.clear_caches()
- self._update_health_status(IntegrationHealthStatusType.HEALTHY)
- logger.debug( 'HASS manager loading completed.' )
- except IntegrationDisabledError:
- msg = 'HASS integration disabled'
- logger.info(msg)
- self._update_health_status( IntegrationHealthStatusType.DISABLED, msg )
- except IntegrationError as e:
- error_msg = f'HASS integration configuration error: {e}'
- logger.error(error_msg)
- self._update_health_status( IntegrationHealthStatusType.CONFIG_ERROR,
- error_msg )
- except IntegrationAttributeError as e:
- error_msg = f'HASS integration attribute error: {e}'
- logger.error(error_msg)
- self._update_health_status( IntegrationHealthStatusType.CONFIG_ERROR,
- error_msg )
- except Exception as e:
- error_msg = f'Unexpected error loading HASS configuration: {e}'
- logger.exception(error_msg)
- self._update_health_status( IntegrationHealthStatusType.TEMPORARY_ERROR,
- error_msg )
+
+ def _reload_implementation( self ):
+ """
+ Perform the actual HASS manager reload work.
+ Called by SingletonManager with appropriate locks already held.
+ """
+ try:
+ self._hass_attr_type_to_attribute = self._load_attributes()
+ self._hass_client = self.create_hass_client( self._hass_attr_type_to_attribute )
+ self.clear_caches()
+ self._update_health_status(IntegrationHealthStatusType.HEALTHY)
+ except IntegrationDisabledError:
+ msg = 'HASS integration disabled'
+ logger.info(msg)
+ self._update_health_status( IntegrationHealthStatusType.DISABLED, msg )
+ except IntegrationError as e:
+ error_msg = f'HASS integration configuration error: {e}'
+ logger.error(error_msg)
+ self._update_health_status( IntegrationHealthStatusType.CONFIG_ERROR,
+ error_msg )
+ except IntegrationAttributeError as e:
+ error_msg = f'HASS integration attribute error: {e}'
+ logger.error(error_msg)
+ self._update_health_status( IntegrationHealthStatusType.CONFIG_ERROR,
+ error_msg )
+ except Exception as e:
+ error_msg = f'Unexpected error loading HASS configuration: {e}'
+ logger.exception(error_msg)
+ self._update_health_status( IntegrationHealthStatusType.TEMPORARY_ERROR,
+ error_msg )
return
def clear_caches(self):
diff --git a/src/hi/services/hass/hass_mixins.py b/src/hi/services/hass/hass_mixins.py
index f8fb423b..4bb3182f 100644
--- a/src/hi/services/hass/hass_mixins.py
+++ b/src/hi/services/hass/hass_mixins.py
@@ -19,7 +19,7 @@ class HassMixin:
if not hasattr( self, '_hass_manager' ):
self._hass_manager = HassManager()
try:
- await asyncio.shield( sync_to_async( self._hass_manager.ensure_initialized )())
+ await asyncio.shield( sync_to_async( self._hass_manager.ensure_initialized, thread_sensitive=True )())
except asyncio.CancelledError:
logger.warning( 'HAss init sync_to_async() was cancelled! Handling gracefully.')
diff --git a/src/hi/services/hass/tests/test_hass_manager.py b/src/hi/services/hass/tests/test_hass_manager.py
index 7e2b9e67..154d2bb1 100644
--- a/src/hi/services/hass/tests/test_hass_manager.py
+++ b/src/hi/services/hass/tests/test_hass_manager.py
@@ -89,30 +89,30 @@ class TestHassManagerInitialization(TestCase):
self.assertFalse(self.manager._was_initialized)
self.assertIsNotNone(self.manager._data_lock)
- @patch('hi.services.hass.hass_manager.HassManager.reload')
- def test_ensure_initialized_calls_reload_once(self, mock_reload):
+ @patch('hi.services.hass.hass_manager.HassManager._reload_implementation')
+ def test_ensure_initialized_calls_reload_once(self, mock_reload_impl):
"""Test ensure_initialized only calls reload once and sets state correctly"""
# Verify initial state
self.assertFalse(self.manager._was_initialized)
-
+
self.manager.ensure_initialized()
- mock_reload.assert_called_once()
+ mock_reload_impl.assert_called_once()
self.assertTrue(self.manager._was_initialized)
-
+
# Second call should not trigger reload but state should remain
self.manager.ensure_initialized()
- mock_reload.assert_called_once() # Still only one call
+ mock_reload_impl.assert_called_once() # Still only one call
self.assertTrue(self.manager._was_initialized)
def test_ensure_initialized_idempotent_behavior(self):
"""Test ensure_initialized can be called multiple times safely"""
- with patch.object(self.manager, 'reload') as mock_reload:
+ with patch.object(self.manager, '_reload_implementation') as mock_reload_impl:
# Call multiple times
for _ in range(5):
self.manager.ensure_initialized()
-
+
# Should only be called once
- mock_reload.assert_called_once()
+ mock_reload_impl.assert_called_once()
self.assertTrue(self.manager._was_initialized)
def test_reload_without_integration_in_database(self):
diff --git a/src/hi/services/zoneminder/constants.py b/src/hi/services/zoneminder/constants.py
index 96627d91..b432e4c1 100644
--- a/src/hi/services/zoneminder/constants.py
+++ b/src/hi/services/zoneminder/constants.py
@@ -1,7 +1,7 @@
class ZmDetailKeys:
"""
ZoneMinder detail_attrs keys used in SensorResponse objects.
-
+
WARNING: These keys are persisted in the database and used across
multiple integrations. Changing them will break compatibility with
historical data and require data migration.
@@ -13,3 +13,32 @@ class ZmDetailKeys:
ALARMED_FRAMES = 'Alarmed Frames'
TOTAL_FRAMES = 'Total Frames'
NOTES = 'Notes'
+
+
+class ZmTimeouts:
+ """
+ Centralized timeout and interval constants for ZoneMinder integration.
+
+ These values are carefully aligned to ensure reliable operation:
+ - API timeout should be less than polling interval to avoid overlapping calls
+ - PyZM client timeout should align with API timeout for consistency
+ - Health check intervals provide regular status updates without overwhelming the system
+ """
+ # Core polling configuration
+ POLLING_INTERVAL_SECS = 4
+ API_TIMEOUT_SECS = 10.0 # Longer than polling to allow for network delays but not too long to block
+
+ # PyZM client timeout (should align with API timeout for consistency)
+ PYZM_CLIENT_TIMEOUT_SECS = 10.0
+
+ # Health check intervals
+ HEALTH_CHECK_INTERVAL_SECS = 30 # Regular health status updates
+ MONITOR_HEARTBEAT_TIMEOUT_SECS = 20 # 5x polling interval = reasonable timeout for heartbeat
+
+ # Cache refresh intervals (from zm_manager.py)
+ STATE_REFRESH_INTERVAL_SECS = 300
+ MONITOR_REFRESH_INTERVAL_SECS = 300
+
+ # Performance thresholds for alerting
+ API_RESPONSE_WARNING_THRESHOLD_SECS = 5.0 # Warn if API calls take longer than this
+ API_RESPONSE_CRITICAL_THRESHOLD_SECS = 8.0 # Critical if API calls approach timeout
diff --git a/src/hi/services/zoneminder/integration.py b/src/hi/services/zoneminder/integration.py
index 81e5a466..7ef2bc72 100644
--- a/src/hi/services/zoneminder/integration.py
+++ b/src/hi/services/zoneminder/integration.py
@@ -57,8 +57,10 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):
def get_health_status(self) -> IntegrationHealthStatus:
"""Get the current health status of the ZoneMinder integration.
-
+
Delegates to ZoneMinderManager for health status information.
+ The health status now includes enhanced monitoring data for debugging
+ transient issues like the bug in #205.
"""
try:
zm_manager = ZoneMinderManager()
diff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.py
index 8e2a284a..6a392110 100644
--- a/src/hi/services/zoneminder/monitors.py
+++ b/src/hi/services/zoneminder/monitors.py
@@ -10,7 +10,7 @@ from hi.apps.sense.sensor_response_manager import SensorResponseMixin
from hi.apps.sense.transient_models import SensorResponse
from hi.apps.sense.enums import CorrelationRole
-from .constants import ZmDetailKeys
+from .constants import ZmDetailKeys, ZmTimeouts
from .zm_models import ZmEvent, AggregatedMonitorState
from .zm_manager import ZoneMinderManager
from .zm_mixins import ZoneMinderMixin
@@ -22,8 +22,10 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
# TODO: Move this into the integrations attributes for users to set
ZONEMINDER_SERVER_TIMEZONE = 'America/Chicago'
- ZONEMINDER_POLLING_INTERVAL_SECS = 4
- ZONEMINDER_API_TIMEOUT_SECS = 10.0 # Shorter timeout appropriate for 4-second polling
+
+ # Use centralized timeout constants
+ ZONEMINDER_POLLING_INTERVAL_SECS = ZmTimeouts.POLLING_INTERVAL_SECS
+ ZONEMINDER_API_TIMEOUT_SECS = ZmTimeouts.API_TIMEOUT_SECS
CACHING_DISABLED = True
@@ -65,7 +67,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
# Reset monitor state so next cycle reinitializes with updated manager
self._was_initialized = False
self._zm_tzname = None # Clear cached timezone
- logger.info( 'ZoneMinderMonitor refreshed - will reinitialize with new settings on next cycle' )
+ logger.debug( 'ZoneMinderMonitor refreshed - will reinitialize with new settings on next cycle' )
return
async def do_work(self):
@@ -76,15 +78,33 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
# Timing issues when first enabling could fail initialization.
logger.warning( 'ZoneMinder monitor failed to initialize. Skipping work cycle.' )
return
-
- sensor_response_map = dict()
- sensor_response_map.update( await self._process_events( ) )
- sensor_response_map.update( await self._process_monitors() )
- sensor_response_map.update( await self._process_states() )
- await self.sensor_response_manager().update_with_latest_sensor_responses(
- sensor_response_map = sensor_response_map,
- )
+ try:
+ # Update heartbeat to indicate monitor is alive and working
+ zm_manager = await self.zm_manager_async()
+ if zm_manager:
+ zm_manager.update_monitor_heartbeat()
+
+ sensor_response_map = dict()
+
+ # Process ZoneMinder events for motion detection
+ sensor_response_map.update( await self._process_events( ) )
+
+ # Process ZoneMinder monitors for function changes
+ sensor_response_map.update( await self._process_monitors() )
+
+ # Process ZoneMinder states for run state changes
+ sensor_response_map.update( await self._process_states() )
+
+ # Update sensor responses
+ await self.sensor_response_manager().update_with_latest_sensor_responses(
+ sensor_response_map = sensor_response_map,
+ )
+
+ except Exception as e:
+ logger.exception(f'ZoneMinder monitor cycle failed: {e}')
+ raise
+
return
async def _process_events(self):
@@ -105,8 +125,11 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
'from': tz_adjusted_poll_from_datetime.isoformat(), # "from" only looks at event start time
'tz': self._zm_tzname,
}
- zm_events = await self.zm_manager().get_zm_events_async( options = options )
- logger.debug( f'Found {len(zm_events)} new ZM events' )
+ try:
+ zm_events = await self.zm_manager().get_zm_events_async( options = options )
+ except Exception as e:
+ logger.error(f'ZoneMinder events API call failed: {e}')
+ raise
# Sensor readings and state value transitions are points in time,
# but ZoneMinder events are intervals. Thus, one ZoneMinder event
@@ -127,7 +150,6 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
closed_zm_event_list = list()
zm_monitor_ids_seen = set()
for zm_api_event in zm_events:
- logger.debug( f'ZM Api Event: {zm_api_event.get()}' )
zm_event = ZmEvent( zm_api_event = zm_api_event,
zm_tzname = self._zm_tzname )
diff --git a/src/hi/services/zoneminder/tests/synthetic_data.py b/src/hi/services/zoneminder/tests/synthetic_data.py
new file mode 100644
index 00000000..18a5e998
--- /dev/null
+++ b/src/hi/services/zoneminder/tests/synthetic_data.py
@@ -0,0 +1,291 @@
+"""
+Synthetic data generators for ZoneMinder testing.
+
+Provides centralized, reusable test data creation following the project's
+synthetic data pattern. Creates real Django ORM objects for testing.
+"""
+
+import uuid
+from typing import Tuple, List
+
+from hi.integrations.models import Integration, IntegrationAttribute
+from hi.integrations.transient_models import IntegrationKey
+
+from hi.services.zoneminder.enums import ZmAttributeType
+from hi.services.zoneminder.zm_metadata import ZmMetaData
+
+
+class ZoneMinderSyntheticData:
+ """Centralized synthetic data generators for ZoneMinder testing."""
+
+ @staticmethod
+ def create_zm_integration(is_enabled: bool = True) -> Integration:
+ """Create a ZoneMinder integration with reasonable defaults."""
+ return Integration.objects.create(
+ integration_id=ZmMetaData.integration_id,
+ is_enabled=is_enabled
+ )
+
+ @staticmethod
+ def create_zm_attribute(
+ integration: Integration,
+ attribute_type: ZmAttributeType,
+ value: str
+ ) -> IntegrationAttribute:
+ """Create a ZoneMinder integration attribute."""
+ integration_key = IntegrationKey(
+ integration_id=ZmMetaData.integration_id,
+ integration_name=str(attribute_type)
+ )
+
+ return IntegrationAttribute.objects.create(
+ integration=integration,
+ integration_key_str=str(integration_key),
+ value=value,
+ is_required=attribute_type.is_required
+ )
+
+ @staticmethod
+ def create_complete_zm_integration(is_enabled: bool = True) -> Tuple[Integration, List[IntegrationAttribute]]:
+ """Create a complete ZoneMinder integration with all required attributes."""
+ # Create the integration
+ integration = ZoneMinderSyntheticData.create_zm_integration(is_enabled=is_enabled)
+
+ # Create all required attributes with realistic values
+ attributes = []
+
+ # API URL - required
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_URL, 'https://zm.test.com/api'
+ ))
+
+ # Portal URL - required
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.PORTAL_URL, 'https://zm.test.com'
+ ))
+
+ # API User - required
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_USER, 'testuser'
+ ))
+
+ # API Password - required
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_PASSWORD, 'testpassword'
+ ))
+
+ # Timezone - required with default
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.TIMEZONE, 'America/Chicago'
+ ))
+
+ return integration, attributes
+
+ @staticmethod
+ def create_minimal_zm_integration() -> Tuple[Integration, List[IntegrationAttribute]]:
+ """Create ZoneMinder integration with only absolutely required attributes."""
+ integration = ZoneMinderSyntheticData.create_zm_integration()
+
+ attributes = []
+
+ # Only create the minimum required attributes
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_URL, 'https://zm.minimal.com/api'
+ ))
+
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.PORTAL_URL, 'https://zm.minimal.com'
+ ))
+
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_USER, 'minimaluser'
+ ))
+
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_PASSWORD, 'minimalpass'
+ ))
+
+ return integration, attributes
+
+ @staticmethod
+ def create_zm_integration_with_optional_attributes() -> Tuple[Integration, List[IntegrationAttribute]]:
+ """Create ZoneMinder integration including optional attributes."""
+ integration, attributes = ZoneMinderSyntheticData.create_complete_zm_integration()
+
+ # Add optional attributes
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.ADD_ALARM_EVENTS, 'true'
+ ))
+
+ return integration, attributes
+
+ @staticmethod
+ def create_invalid_zm_integration() -> Tuple[Integration, List[IntegrationAttribute]]:
+ """Create ZoneMinder integration with invalid attribute values for testing."""
+ integration = ZoneMinderSyntheticData.create_zm_integration()
+
+ attributes = []
+
+ # Create attributes with invalid values
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_URL, 'not-a-valid-url'
+ ))
+
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.PORTAL_URL, 'also-not-valid'
+ ))
+
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_USER, '' # Empty user
+ ))
+
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_PASSWORD, '' # Empty password
+ ))
+
+ return integration, attributes
+
+ @staticmethod
+ def create_zm_integration_missing_required() -> Tuple[Integration, List[IntegrationAttribute]]:
+ """Create ZoneMinder integration missing required attributes for error testing."""
+ integration = ZoneMinderSyntheticData.create_zm_integration()
+
+ attributes = []
+
+ # Only create some required attributes, missing others
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_URL, 'https://zm.partial.com/api'
+ ))
+
+ attributes.append(ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.PORTAL_URL, 'https://zm.partial.com'
+ ))
+
+ # Missing API_USER and API_PASSWORD intentionally
+
+ return integration, attributes
+
+ @staticmethod
+ def create_multiple_zm_integrations() -> List[Integration]:
+ """Create multiple ZoneMinder integrations for multi-instance testing."""
+ integrations = []
+
+ # Create multiple integrations with different configurations
+ for i in range(3):
+ unique_id = str(uuid.uuid4())[:8]
+ integration = Integration.objects.create(
+ integration_id=f'zm_{unique_id}',
+ is_enabled=True
+ )
+
+ # Add basic required attributes
+ ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_URL, f'https://zm{i+1}.test.com/api'
+ )
+ ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.PORTAL_URL, f'https://zm{i+1}.test.com'
+ )
+ ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_USER, f'user{i+1}'
+ )
+ ZoneMinderSyntheticData.create_zm_attribute(
+ integration, ZmAttributeType.API_PASSWORD, f'pass{i+1}'
+ )
+
+ integrations.append(integration)
+
+ return integrations
+
+ @staticmethod
+ def create_attribute_mapping_dict(attributes: List[IntegrationAttribute]) -> dict:
+ """Convert list of IntegrationAttributes to ZmAttributeType mapping dict."""
+ mapping = {}
+
+ for attr in attributes:
+ # Parse the attribute type from the integration key
+ attr_type = ZmAttributeType.from_name_safe(attr.integration_key.integration_name)
+ if attr_type:
+ mapping[attr_type] = attr
+
+ return mapping
+
+ @staticmethod
+ def create_test_zm_states_data() -> List[dict]:
+ """Create test ZoneMinder states data for API response mocking."""
+ return [
+ {
+ 'State': {
+ 'Id': '1',
+ 'Name': 'default',
+ 'Definition': '[{"Id":"1","Function":"Monitor"},{"Id":"2","Function":"Modect"}]'
+ }
+ },
+ {
+ 'State': {
+ 'Id': '2',
+ 'Name': 'alert',
+ 'Definition': '[{"Id":"1","Function":"Modect"},{"Id":"2","Function":"Record"}]'
+ }
+ }
+ ]
+
+ @staticmethod
+ def create_test_zm_monitors_data() -> List[dict]:
+ """Create test ZoneMinder monitors data for API response mocking."""
+ return [
+ {
+ 'Monitor': {
+ 'Id': '1',
+ 'Name': 'Front Door',
+ 'Function': 'Modect',
+ 'Enabled': '1',
+ 'Type': 'Remote',
+ 'Host': '192.168.1.100',
+ 'Path': '/videostream.cgi',
+ }
+ },
+ {
+ 'Monitor': {
+ 'Id': '2',
+ 'Name': 'Back Yard',
+ 'Function': 'Monitor',
+ 'Enabled': '1',
+ 'Type': 'Remote',
+ 'Host': '192.168.1.101',
+ 'Path': '/videostream.cgi',
+ }
+ }
+ ]
+
+ @staticmethod
+ def create_test_zm_events_data() -> List[dict]:
+ """Create test ZoneMinder events data for API response mocking."""
+ return [
+ {
+ 'Event': {
+ 'Id': '1001',
+ 'MonitorId': '1',
+ 'Name': 'Motion Detection',
+ 'Cause': 'Motion',
+ 'StartTime': '2023-01-01 10:00:00',
+ 'EndTime': '2023-01-01 10:00:30',
+ 'Length': '30.00',
+ 'Frames': '150',
+ 'AlarmFrames': '15'
+ }
+ },
+ {
+ 'Event': {
+ 'Id': '1002',
+ 'MonitorId': '2',
+ 'Name': 'Object Detection',
+ 'Cause': 'Motion',
+ 'StartTime': '2023-01-01 11:00:00',
+ 'EndTime': '2023-01-01 11:01:00',
+ 'Length': '60.00',
+ 'Frames': '300',
+ 'AlarmFrames': '25'
+ }
+ }
+ ]
+
diff --git a/src/hi/services/zoneminder/tests/test_zm_manager.py b/src/hi/services/zoneminder/tests/test_zm_manager.py
index 04f8c6ff..98a79c2c 100644
--- a/src/hi/services/zoneminder/tests/test_zm_manager.py
+++ b/src/hi/services/zoneminder/tests/test_zm_manager.py
@@ -1,647 +1,412 @@
-import logging
+"""
+Tests for ZoneMinderManager class.
+
+Focus on testing behavior and outcomes, not implementation details.
+Uses real Django models and only mocks external HTTP calls.
+"""
+
import threading
-from datetime import timedelta
-from unittest.mock import Mock, patch
-from django.test import TestCase
-import pytz
+from unittest.mock import patch, Mock, MagicMock
+from concurrent.futures import ThreadPoolExecutor, as_completed
-import hi.apps.common.datetimeproxy as datetimeproxy
-from hi.integrations.enums import IntegrationHealthStatusType
-from hi.integrations.exceptions import IntegrationAttributeError
-from hi.integrations.transient_models import IntegrationKey
-from hi.integrations.models import Integration, IntegrationAttribute
+from django.test import TestCase, TransactionTestCase
-from hi.services.zoneminder.enums import ZmAttributeType
+from hi.integrations.models import Integration, IntegrationAttribute
+from hi.integrations.enums import IntegrationHealthStatusType
from hi.services.zoneminder.zm_manager import ZoneMinderManager
+from hi.services.zoneminder.enums import ZmAttributeType
from hi.services.zoneminder.zm_metadata import ZmMetaData
-logging.disable(logging.CRITICAL)
+class ZoneMinderManagerSingletonTest(TestCase):
+ """Test singleton behavior of ZoneMinderManager."""
-class TestZoneMinderManagerSingleton(TestCase):
- """Test singleton behavior and thread safety"""
-
- def setUp(self):
- # Reset singleton instance for each test
- ZoneMinderManager._instance = None
- ZoneMinderManager._lock = threading.Lock()
-
- def test_singleton_behavior(self):
- """Test that ZoneMinderManager follows singleton pattern"""
+ def test_singleton_returns_same_instance(self):
+ """Multiple calls should return the same instance."""
manager1 = ZoneMinderManager()
manager2 = ZoneMinderManager()
self.assertIs(manager1, manager2)
-
- def test_singleton_thread_safety(self):
- """Test singleton creation is thread-safe"""
- results = []
-
+
+ def test_singleton_thread_safe(self):
+ """Singleton should be thread-safe."""
+ managers = []
+
def create_manager():
- results.append(ZoneMinderManager())
-
- threads = [threading.Thread(target=create_manager) for _ in range(5)]
- for thread in threads:
- thread.start()
- for thread in threads:
- thread.join()
-
- # All instances should be the same object
- first_instance = results[0]
- for instance in results[1:]:
- self.assertIs(instance, first_instance)
-
-
-class TestZoneMinderManagerInitialization(TestCase):
- """Test initialization and attribute loading"""
-
+ managers.append(ZoneMinderManager())
+
+ # Create multiple threads trying to instantiate simultaneously
+ with ThreadPoolExecutor(max_workers=5) as executor:
+ futures = [executor.submit(create_manager) for _ in range(10)]
+ for future in as_completed(futures):
+ future.result() # Wait for completion
+
+ # All should be the same instance
+ first = managers[0]
+ for manager in managers[1:]:
+ self.assertIs(manager, first)
+
+
+class ZoneMinderManagerConfigurationTest(TransactionTestCase):
+ """Test configuration loading and validation behavior."""
+
def setUp(self):
- ZoneMinderManager._instance = None
- ZoneMinderManager._lock = threading.Lock()
- self.manager = ZoneMinderManager()
-
- def test_init_singleton_sets_defaults(self):
- """Test singleton initialization sets correct defaults"""
- self.assertEqual(self.manager._zm_attr_type_to_attribute, {})
- self.assertIsNone(self.manager._zm_client)
- self.assertEqual(self.manager._zm_state_list, [])
- self.assertEqual(self.manager._zm_monitor_list, [])
- self.assertEqual(self.manager._change_listeners, set())
- self.assertFalse(self.manager._was_initialized)
- self.assertIsNotNone(self.manager._data_lock)
-
- @patch('hi.services.zoneminder.zm_manager.ZoneMinderManager.reload')
- def test_ensure_initialized_calls_reload_once(self, mock_reload):
- """Test ensure_initialized only calls reload once"""
- self.manager.ensure_initialized()
- mock_reload.assert_called_once()
-
- # Second call should not trigger reload
- self.manager.ensure_initialized()
- mock_reload.assert_called_once() # Still only one call
-
- self.assertTrue(self.manager._was_initialized)
-
- def test_reload_without_integration_in_database(self):
- """Test reload handles missing integration gracefully"""
- # Don't create any Integration in the database
- self.manager.reload()
-
- # Manager should still be functional, just with no configuration
- self.assertIsNotNone(self.manager)
- # Health status should reflect the configuration error
- health = self.manager.get_health_status()
- self.assertEqual(health.status, IntegrationHealthStatusType.CONFIG_ERROR)
- self.assertIn('not implemented', health.error_message)
-
- def test_reload_with_disabled_integration(self):
- """Test reload handles disabled integration gracefully"""
- # Create a disabled integration
- Integration.objects.create(
- integration_id=ZmMetaData.integration_id,
- is_enabled=False
- )
-
- self.manager.reload()
-
- # Health status should reflect the configuration error
- health = self.manager.get_health_status()
- self.assertEqual(health.status, IntegrationHealthStatusType.DISABLED)
-
- def test_reload_with_missing_required_attribute(self):
- """Test reload handles missing required attributes gracefully"""
- # Create an enabled integration but without required attributes
- Integration.objects.create(
+ """Create test integration and attributes."""
+ self.integration = Integration.objects.create(
integration_id=ZmMetaData.integration_id,
is_enabled=True
)
- # Don't create any attributes - missing required ones
-
- self.manager.reload()
-
- # Health status should reflect the configuration error
- health = self.manager.get_health_status()
+
+ # Create required attributes
+ self.create_attribute(ZmAttributeType.API_URL, 'http://test.zm/api')
+ self.create_attribute(ZmAttributeType.PORTAL_URL, 'http://test.zm')
+ self.create_attribute(ZmAttributeType.API_USER, 'testuser')
+ self.create_attribute(ZmAttributeType.API_PASSWORD, 'testpass')
+ self.create_attribute(ZmAttributeType.TIMEZONE, 'America/Chicago')
+
+ def tearDown(self):
+ """Clean up singleton instance for next test."""
+ # Reset singleton instance
+ ZoneMinderManager._instance = None
+
+ def create_attribute(self, attr_type, value):
+ """Helper to create integration attributes."""
+ return IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{str(attr_type)}",
+ value=value,
+ is_required=attr_type.is_required
+ )
+
+ @patch('hi.services.zoneminder.zm_client_factory.ZmClientFactory.create_client')
+ def test_loads_configuration_on_first_access(self, mock_create_client):
+ """Configuration should be loaded on first client access."""
+ mock_client = Mock()
+ mock_create_client.return_value = mock_client
+
+ manager = ZoneMinderManager()
+
+ # Access client property - should trigger loading
+ client = manager.zm_client
+
+ # Verify client was created
+ self.assertIsNotNone(client)
+ mock_create_client.assert_called_once()
+
+ def test_handles_missing_integration(self):
+ """Should handle missing integration gracefully."""
+ # Delete the integration
+ self.integration.delete()
+
+ manager = ZoneMinderManager()
+
+ # Should not crash but client should be None
+ client = manager.zm_client
+ self.assertIsNone(client)
+
+ # Health status should reflect the error
+ health = manager.get_health_status()
+ self.assertFalse(health.is_healthy)
+
+ def test_handles_disabled_integration(self):
+ """Should handle disabled integration gracefully."""
+ self.integration.is_enabled = False
+ self.integration.save()
+
+ manager = ZoneMinderManager()
+ client = manager.zm_client
+
+ self.assertIsNone(client)
+ health = manager.get_health_status()
+ self.assertEqual(health.status, IntegrationHealthStatusType.DISABLED)
+
+ def test_validates_required_attributes(self):
+ """Should validate that required attributes are present."""
+ # Delete a required attribute
+ IntegrationAttribute.objects.filter(
+ integration_key_str__contains=str(ZmAttributeType.API_URL)
+ ).delete()
+
+ manager = ZoneMinderManager()
+ client = manager.zm_client
+
+ # Should handle missing required attribute
+ self.assertIsNone(client)
+ health = manager.get_health_status()
self.assertEqual(health.status, IntegrationHealthStatusType.CONFIG_ERROR)
- self.assertIn('Missing ZM attribute', health.error_message)
-
- def test_reload_with_empty_required_value(self):
- """Test reload handles empty required attribute values gracefully"""
- # Create a real integration in the database
- integration = Integration.objects.create(
+
+
+class ZoneMinderManagerThreadLocalTest(TransactionTestCase):
+ """Test thread-local client behavior."""
+
+ def setUp(self):
+ """Create test integration and attributes."""
+ self.integration = Integration.objects.create(
integration_id=ZmMetaData.integration_id,
is_enabled=True
)
-
- # Create an attribute with whitespace-only value
- attr = IntegrationAttribute.objects.create(
- integration=integration,
- name=str(ZmAttributeType.API_URL),
- value=' ', # Whitespace only
+
+ # Create required attributes
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.API_URL}",
+ value='http://test.zm/api',
is_required=True
)
- attr.integration_key = IntegrationKey(
- integration_id=ZmMetaData.integration_id,
- integration_name=str(ZmAttributeType.API_URL)
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.PORTAL_URL}",
+ value='http://test.zm',
+ is_required=True
)
- attr.save()
-
- # Reload should handle this gracefully
- self.manager.reload()
-
- # Health status should reflect the configuration error
- health = self.manager.get_health_status()
- self.assertEqual(health.status, IntegrationHealthStatusType.CONFIG_ERROR)
- self.assertIn('Missing ZM attribute', health.error_message)
-
- def test_reload_success_with_all_required_attributes(self):
- """Test reload successfully configures manager with all required attributes"""
- # Create a real integration in the database
- integration = Integration.objects.create(
- integration_id=ZmMetaData.integration_id,
- is_enabled=True
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.API_USER}",
+ value='testuser',
+ is_required=True
)
-
- # Create all required attributes with valid values
- for attr_type in ZmAttributeType:
- if attr_type.is_required:
- attr = IntegrationAttribute.objects.create(
- integration=integration,
- name=str(attr_type),
- value=f'test_value_{attr_type.name}',
- is_required=True
- )
- attr.integration_key = IntegrationKey(
- integration_id=ZmMetaData.integration_id,
- integration_name=str(attr_type)
- )
- attr.save()
-
- # Reload should configure the manager successfully
- self.manager.reload()
-
- # Health status should not have missing attribute errors
- health = self.manager.get_health_status()
- # Note: might still have connection errors if ZM API is unreachable,
- # but no missing attribute config errors
- self.assertNotIn('Missing ZM attribute', health.error_message)
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.API_PASSWORD}",
+ value='testpass',
+ is_required=True
+ )
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.TIMEZONE}",
+ value='America/Chicago',
+ is_required=True
+ )
+
+ def tearDown(self):
+ """Clean up singleton instance for next test."""
+ ZoneMinderManager._instance = None
+
+ @patch('hi.services.zoneminder.zm_client_factory.ZmClientFactory.create_client')
+ def test_each_thread_gets_own_client(self, mock_create_client):
+ """Each thread should get its own client instance."""
+ # Track which clients are created
+ call_count = [0] # Use list to modify in nested function
+
+ def create_mock_client(*args, **kwargs):
+ call_count[0] += 1
+ # Create unique mock for each call
+ mock = MagicMock()
+ mock.id = call_count[0] # Give each a unique ID
+ return mock
+ mock_create_client.side_effect = create_mock_client
+
+ manager = ZoneMinderManager()
+ results = {}
+ event = threading.Event()
+
+ def get_client(thread_name):
+ client = manager.zm_client
+ results[thread_name] = client
+ event.set()
+
+ # Get client from main thread
+ main_client = manager.zm_client
+ results['main'] = main_client
+
+ # Get client from another thread
+ thread = threading.Thread(target=get_client, args=('thread1',))
+ thread.start()
+ thread.join(timeout=1)
+
+ # Each thread should have gotten a different client
+ self.assertIsNotNone(results.get('main'))
+ self.assertIsNotNone(results.get('thread1'))
+ # Different mock objects should have different IDs
+ self.assertNotEqual(results['main'].id, results['thread1'].id)
+ # Should have created 2 clients
+ self.assertEqual(call_count[0], 2)
+
+
+class ZoneMinderManagerHealthStatusTest(TestCase):
+ """Test health status tracking behavior."""
-class TestZoneMinderManagerClientCreation(TestCase):
- """Test ZM client creation and API option validation"""
-
def setUp(self):
+ """Create test integration."""
+ self.integration = Integration.objects.create(
+ integration_id=ZmMetaData.integration_id,
+ is_enabled=True
+ )
+ # Add minimal required attributes
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.API_URL}",
+ value='http://test.zm/api',
+ is_required=True
+ )
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.PORTAL_URL}",
+ value='http://test.zm',
+ is_required=True
+ )
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.API_USER}",
+ value='testuser',
+ is_required=True
+ )
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.API_PASSWORD}",
+ value='testpass',
+ is_required=True
+ )
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.TIMEZONE}",
+ value='America/Chicago',
+ is_required=True
+ )
+
+ def tearDown(self):
+ """Clean up singleton instance."""
ZoneMinderManager._instance = None
- ZoneMinderManager._lock = threading.Lock()
- self.manager = ZoneMinderManager()
-
- def create_mock_attributes(self):
- """Helper to create mock attributes for client creation"""
- attributes = {}
- attr_values = {
- ZmAttributeType.API_URL: 'https://test.com/zm/api',
- ZmAttributeType.PORTAL_URL: 'https://test.com/zm',
- ZmAttributeType.API_USER: 'testuser',
- ZmAttributeType.API_PASSWORD: 'testpass'
- }
-
- for attr_type, value in attr_values.items():
- mock_attr = Mock()
- mock_attr.value = value
- mock_attr.integration_key = IntegrationKey(
- integration_id=ZmMetaData.integration_id,
- integration_name=str(attr_type)
- )
- attributes[attr_type] = mock_attr
-
- return attributes
-
- def test_create_zm_client_missing_api_attribute(self):
- """Test create_zm_client raises error for missing API attributes"""
- incomplete_attributes = {
- ZmAttributeType.API_URL: Mock(value='https://test.com/api')
- # Missing other required API attributes
- }
-
- with self.assertRaises(IntegrationAttributeError) as context:
- self.manager.create_zm_client(incomplete_attributes)
-
- self.assertIn('Missing ZM API attribute', str(context.exception))
-
- def test_create_zm_client_empty_api_attribute_value(self):
- """Test create_zm_client raises error for empty API attribute values"""
- attributes = self.create_mock_attributes()
- attributes[ZmAttributeType.API_URL].value = ' ' # Empty value
-
- with self.assertRaises(IntegrationAttributeError) as context:
- self.manager.create_zm_client(attributes)
-
- self.assertIn('Missing ZM API attribute value for', str(context.exception))
-
- @patch('hi.services.zoneminder.zm_client_factory.ZMApi')
- def test_create_zm_client_success(self, mock_zmapi_class):
- """Test create_zm_client successfully delegates to factory"""
- # Arrange
+
+ def test_tracks_health_status(self):
+ """Should track health status of integration."""
+ manager = ZoneMinderManager()
+ health = manager.get_health_status()
+
+ # Should have health status
+ self.assertIsNotNone(health)
+ self.assertIsNotNone(health.last_check)
+ self.assertIsNotNone(health.status)
+
+ def test_updates_monitor_heartbeat(self):
+ """Should update monitor heartbeat timestamp."""
+ manager = ZoneMinderManager()
+
+ # Get initial heartbeat
+ health1 = manager.get_health_status()
+ initial_heartbeat = health1.monitor_heartbeat
+
+ # Update heartbeat
+ manager.update_monitor_heartbeat()
+
+ # Should have newer heartbeat
+ health2 = manager.get_health_status()
+ self.assertIsNotNone(health2.monitor_heartbeat)
+ if initial_heartbeat:
+ self.assertGreaterEqual(health2.monitor_heartbeat, initial_heartbeat)
+
+ @patch('hi.services.zoneminder.zm_client_factory.ZmClientFactory.create_client')
+ def test_tracks_api_metrics(self, mock_create_client):
+ """Should track API call metrics."""
+ # Create a mock client with states method
mock_client = Mock()
- mock_zmapi_class.return_value = mock_client
- attributes = self.create_mock_attributes()
+ mock_states = Mock()
+ mock_states.list.return_value = []
+ mock_client.states.return_value = mock_states
+ mock_create_client.return_value = mock_client
- # For now, just test that the manager has a factory and delegates properly
- # The actual ZMApi creation with network calls is tested in the factory tests
- self.assertIsNotNone(self.manager._client_factory)
- self.assertTrue(hasattr(self.manager._client_factory, 'create_client'))
+ manager = ZoneMinderManager()
- # Act - Test that calling create_zm_client delegates to factory properly
- result = self.manager.create_zm_client(attributes)
+ # Make an API call - this should use our mocked client
+ manager.get_zm_states(force_load=True)
- # Assert - Test delegation behavior without network calls
- self.assertIs(result, mock_client)
- mock_zmapi_class.assert_called_once()
+ # Check metrics were updated
+ health = manager.get_health_status()
+ self.assertIsNotNone(health.api_metrics)
+ self.assertGreaterEqual(health.api_metrics['total_calls'], 0)
+ def test_connection_test_updates_health(self):
+ """Connection test should update health status."""
+ manager = ZoneMinderManager()
-class TestZoneMinderManagerCaching(TestCase):
- """Test TTL caching logic for states and monitors"""
-
- def setUp(self):
- ZoneMinderManager._instance = None
- ZoneMinderManager._lock = threading.Lock()
- self.manager = ZoneMinderManager()
-
- # Mock the zm_client
- self.mock_client = Mock()
- self.manager._zm_client = self.mock_client
-
- @patch('hi.apps.common.datetimeproxy.now')
- def test_get_zm_states_cache_miss_empty_list(self, mock_now):
- """Test get_zm_states fetches from API when list is empty and updates cache"""
- test_time = datetimeproxy.datetime.datetime(2023, 1, 1, 12, 0, 0, tzinfo=pytz.UTC)
- mock_now.return_value = test_time
-
- # Create mock states with some identifiable data
- mock_state1 = Mock()
- mock_state1.get.return_value = {'State': {'Name': 'state1'}}
- mock_state2 = Mock()
- mock_state2.get.return_value = {'State': {'Name': 'state2'}}
- mock_states = [mock_state1, mock_state2]
- self.mock_client.states.return_value.list.return_value = mock_states
-
- # Verify initial cache state is empty
- self.assertEqual(self.manager._zm_state_list, [])
- self.assertEqual(self.manager._zm_state_timestamp, datetimeproxy.min())
-
- result = self.manager.get_zm_states()
-
- # Verify behavior: returns the correct states
- self.assertEqual(result, mock_states)
- self.assertEqual(len(result), 2)
-
- # Verify state changes: cache is populated and timestamp updated
- self.assertEqual(self.manager._zm_state_list, mock_states)
- self.assertEqual(self.manager._zm_state_timestamp, test_time)
-
- # Verify API was called (secondary to behavior verification)
- self.mock_client.states.assert_called_once()
- self.mock_client.states.return_value.list.assert_called_once()
-
- @patch('hi.apps.common.datetimeproxy.now')
- def test_get_zm_states_cache_hit_within_ttl(self, mock_now):
- """Test get_zm_states returns cached data within TTL without API call"""
- start_time = datetimeproxy.datetime.datetime(2023, 1, 1, 12, 0, 0, tzinfo=pytz.UTC)
- mock_now.return_value = start_time
-
- # Set up cached data with identifiable content
- cached_state1 = Mock()
- cached_state1.get.return_value = {'State': {'Name': 'cached_state1'}}
- cached_state2 = Mock()
- cached_state2.get.return_value = {'State': {'Name': 'cached_state2'}}
- cached_states = [cached_state1, cached_state2]
- self.manager._zm_state_list = cached_states
- self.manager._zm_state_timestamp = start_time
-
- # Advance time by less than TTL (300 seconds)
- mock_now.return_value = start_time + timedelta(seconds=200)
-
- result = self.manager.get_zm_states()
-
- # Verify behavior: returns exact cached data
- self.assertIs(result, cached_states)
- self.assertEqual(len(result), 2)
-
- # Verify state unchanged: cache timestamp and content remain the same
- self.assertEqual(self.manager._zm_state_timestamp, start_time)
- self.assertIs(self.manager._zm_state_list, cached_states)
-
- # Verify no API call was made (important for caching behavior)
- self.mock_client.states.assert_not_called()
-
- @patch('hi.apps.common.datetimeproxy.now')
- def test_get_zm_states_cache_miss_expired_ttl(self, mock_now):
- """Test get_zm_states fetches from API when TTL expired"""
- start_time = datetimeproxy.datetime.datetime(2023, 1, 1, 12, 0, 0, tzinfo=pytz.UTC)
-
- # Set up cached data
- cached_states = [Mock(), Mock()]
- self.manager._zm_state_list = cached_states
- self.manager._zm_state_timestamp = start_time
-
- # Advance time beyond TTL (300 seconds)
- mock_now.return_value = start_time + timedelta(seconds=400)
-
- new_states = [Mock(), Mock(), Mock()]
- self.mock_client.states.return_value.list.return_value = new_states
-
- result = self.manager.get_zm_states()
-
- self.mock_client.states.assert_called_once()
- self.assertEqual(result, new_states)
- self.assertEqual(self.manager._zm_state_list, new_states)
-
- def test_get_zm_states_force_load_bypasses_cache(self):
- """Test get_zm_states with force_load=True bypasses cache"""
- # Set up cached data
- cached_states = [Mock(), Mock()]
- self.manager._zm_state_list = cached_states
- self.manager._zm_state_timestamp = datetimeproxy.now()
-
- new_states = [Mock(), Mock(), Mock()]
- self.mock_client.states.return_value.list.return_value = new_states
-
- result = self.manager.get_zm_states(force_load=True)
-
- self.mock_client.states.assert_called_once()
- self.assertEqual(result, new_states)
-
- @patch('hi.apps.common.datetimeproxy.now')
- def test_get_zm_monitors_cache_behavior(self, mock_now):
- """Test get_zm_monitors follows same caching pattern as states"""
- test_time = datetimeproxy.datetime.datetime(2023, 1, 1, 12, 0, 0, tzinfo=pytz.UTC)
- mock_now.return_value = test_time
-
- mock_monitors = [Mock(), Mock()]
- self.mock_client.monitors.return_value.list.return_value = mock_monitors
-
- result = self.manager.get_zm_monitors()
-
- # Verify force_reload option is passed to pyzm
- expected_options = {'force_reload': True}
- self.mock_client.monitors.assert_called_once_with(expected_options)
- self.assertEqual(result, mock_monitors)
-
- def test_clear_caches_resets_cached_data(self):
- """Test clear_caches resets both state and monitor caches"""
- # Set up cached data
- self.manager._zm_state_list = [Mock(), Mock()]
- self.manager._zm_monitor_list = [Mock(), Mock(), Mock()]
-
- self.manager.clear_caches()
-
- self.assertEqual(self.manager._zm_state_list, [])
- self.assertEqual(self.manager._zm_monitor_list, [])
+ # Test connection (will fail without real API)
+ _ = manager.test_connection()
+ # Should update health status even on failure
+ health = manager.get_health_status()
+ self.assertIsNotNone(health.status)
+ self.assertIsNotNone(health.last_check)
-class TestZoneMinderManagerTimezoneValidation(TestCase):
- """Test complex timezone validation business logic"""
-
- def setUp(self):
- ZoneMinderManager._instance = None
- ZoneMinderManager._lock = threading.Lock()
- self.manager = ZoneMinderManager()
-
- @patch.object(Integration.objects, 'get')
- @patch.object(IntegrationAttribute.objects, 'filter')
- @patch('hi.apps.common.datetimeproxy.is_valid_timezone_name')
- def test_get_zm_tzname_valid_timezone(self, mock_is_valid, mock_filter, mock_get):
- """Test get_zm_tzname returns valid timezone"""
- mock_integration = Mock()
- mock_get.return_value = mock_integration
-
- mock_attr = Mock()
- mock_attr.value = 'America/Chicago'
- mock_filter.return_value.first.return_value = mock_attr
-
- mock_is_valid.return_value = True
-
- result = self.manager.get_zm_tzname()
-
- self.assertEqual(result, 'America/Chicago')
- mock_is_valid.assert_called_once_with(tz_name='America/Chicago')
-
- @patch.object(Integration.objects, 'get')
- @patch.object(IntegrationAttribute.objects, 'filter')
- @patch('hi.apps.common.datetimeproxy.is_valid_timezone_name')
- def test_get_zm_tzname_invalid_timezone_fallback(self, mock_is_valid, mock_filter, mock_get):
- """Test get_zm_tzname falls back to UTC for invalid timezone"""
- mock_integration = Mock()
- mock_get.return_value = mock_integration
-
- mock_attr = Mock()
- mock_attr.value = 'Invalid/Timezone'
- mock_filter.return_value.first.return_value = mock_attr
-
- mock_is_valid.return_value = False
-
- result = self.manager.get_zm_tzname()
-
- self.assertEqual(result, 'UTC')
-
- @patch.object(Integration.objects, 'get')
- @patch.object(IntegrationAttribute.objects, 'filter')
- def test_get_zm_tzname_no_attribute_fallback(self, mock_filter, mock_get):
- """Test get_zm_tzname falls back to UTC when no attribute found"""
- mock_integration = Mock()
- mock_get.return_value = mock_integration
-
- mock_filter.return_value.first.return_value = None
-
- result = self.manager.get_zm_tzname()
-
- self.assertEqual(result, 'UTC')
-
- @patch.object(Integration.objects, 'get')
- def test_get_zm_tzname_integration_not_found_fallback(self, mock_get):
- """Test get_zm_tzname falls back to UTC when integration not found"""
- mock_get.side_effect = Integration.DoesNotExist
-
- result = self.manager.get_zm_tzname()
-
- self.assertEqual(result, 'UTC')
-
- @patch.object(Integration.objects, 'get')
- @patch.object(IntegrationAttribute.objects, 'filter')
- def test_get_zm_tzname_integration_attribute_not_found_fallback(self, mock_filter, mock_get):
- """Test get_zm_tzname falls back to UTC when integration attribute not found"""
- mock_integration = Mock()
- mock_get.return_value = mock_integration
-
- # Simulate IntegrationAttribute.DoesNotExist by making filter().first() raise it
- mock_filter.return_value.first.side_effect = IntegrationAttribute.DoesNotExist
-
- result = self.manager.get_zm_tzname()
-
- self.assertEqual(result, 'UTC')
+class ZoneMinderManagerReloadTest(TransactionTestCase):
+ """Test configuration reload behavior."""
-class TestZoneMinderManagerChangeListeners(TestCase):
- """Test change listener callback system and thread safety"""
-
def setUp(self):
+ """Create test integration."""
+ self.integration = Integration.objects.create(
+ integration_id=ZmMetaData.integration_id,
+ is_enabled=True
+ )
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.API_URL}",
+ value='http://test.zm/api',
+ is_required=True
+ )
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.PORTAL_URL}",
+ value='http://test.zm',
+ is_required=True
+ )
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.API_USER}",
+ value='testuser',
+ is_required=True
+ )
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.API_PASSWORD}",
+ value='testpass',
+ is_required=True
+ )
+ IntegrationAttribute.objects.create(
+ integration=self.integration,
+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.TIMEZONE}",
+ value='America/Chicago',
+ is_required=True
+ )
+
+ def tearDown(self):
+ """Clean up singleton instance."""
ZoneMinderManager._instance = None
- ZoneMinderManager._lock = threading.Lock()
- self.manager = ZoneMinderManager()
-
- def test_register_change_listener(self):
- """Test registering change listeners"""
- callback1 = Mock()
- callback2 = Mock()
-
- self.manager.register_change_listener(callback1)
- self.manager.register_change_listener(callback2)
-
- self.assertEqual(len(self.manager._change_listeners), 2)
- self.assertIn(callback1, self.manager._change_listeners)
- self.assertIn(callback2, self.manager._change_listeners)
-
- def test_register_change_listener_prevents_duplicates(self):
- """Test that registering the same listener multiple times only adds it once"""
- callback = Mock()
-
- # Register the same callback multiple times
- self.manager.register_change_listener(callback)
- self.manager.register_change_listener(callback)
- self.manager.register_change_listener(callback)
-
- # Should only be registered once
- self.assertEqual(len(self.manager._change_listeners), 1)
- self.assertIn(callback, self.manager._change_listeners)
-
- # Verify it's only called once when settings change
- self.manager.notify_settings_changed()
- callback.assert_called_once()
-
- @patch.object(ZoneMinderManager, 'reload')
- def test_notify_settings_changed_calls_reload_and_listeners(self, mock_reload):
- """Test notify_settings_changed triggers reload and notifies all registered listeners"""
- # Create trackable callback functions
- callback1_called = []
- callback2_called = []
-
- def callback1():
- callback1_called.append(True)
-
- def callback2():
- callback2_called.append(True)
-
- # Verify initial state: no listeners registered
- self.assertEqual(len(self.manager._change_listeners), 0)
-
- # Register listeners and verify they are stored
- self.manager.register_change_listener(callback1)
- self.manager.register_change_listener(callback2)
- self.assertEqual(len(self.manager._change_listeners), 2)
-
- # Verify initial callback state
- self.assertEqual(len(callback1_called), 0)
- self.assertEqual(len(callback2_called), 0)
-
- self.manager.notify_settings_changed()
-
- # Verify behavior: reload was triggered
- mock_reload.assert_called_once()
-
- # Verify behavior: all callbacks were executed
- self.assertEqual(len(callback1_called), 1)
- self.assertEqual(len(callback2_called), 1)
-
- # Verify state: listeners remain registered for future notifications
- self.assertEqual(len(self.manager._change_listeners), 2)
-
- @patch.object(ZoneMinderManager, 'reload')
- def test_notify_settings_changed_handles_callback_exceptions(self, mock_reload):
- """Test notify_settings_changed continues if callback raises exception"""
- callback1 = Mock()
- callback2 = Mock(side_effect=Exception("Test exception"))
- callback3 = Mock()
-
- self.manager.register_change_listener(callback1)
- self.manager.register_change_listener(callback2)
- self.manager.register_change_listener(callback3)
-
- # Should not raise exception despite callback2 failing
- self.manager.notify_settings_changed()
-
- # All callbacks should be attempted
- callback1.assert_called_once()
- callback2.assert_called_once()
- callback3.assert_called_once()
+ @patch('hi.services.zoneminder.zm_client_factory.ZmClientFactory.create_client')
+ def test_reload_clears_thread_local_clients(self, mock_create_client):
+ """Reload should clear thread-local clients."""
+ mock_create_client.return_value = Mock()
-class TestZoneMinderManagerUrlGeneration(TestCase):
- """Test URL generation for video streams"""
-
- def setUp(self):
- ZoneMinderManager._instance = None
- ZoneMinderManager._lock = threading.Lock()
- self.manager = ZoneMinderManager()
-
- # Mock client with portal URL
- self.mock_client = Mock()
- self.mock_client.portal_url = 'https://test.com/zm'
- self.manager._zm_client = self.mock_client
-
- def test_get_video_stream_url(self):
- """Test video stream URL generation"""
- monitor_id = 123
- expected_url = 'https://test.com/zm/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&monitor=123'
-
- result = self.manager.get_video_stream_url(monitor_id)
-
- self.assertEqual(result, expected_url)
-
- def test_get_event_video_stream_url(self):
- """Test event video stream URL generation"""
- event_id = 456
- expected_base_url = (
- 'https://test.com/zm/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&'
- 'maxfps=5&replay=single&source=event&event=456&_t='
- )
-
- result = self.manager.get_event_video_stream_url(event_id)
-
- # Check that URL starts with expected base and includes timestamp
- self.assertTrue(result.startswith(expected_base_url))
-
- # Extract and validate timestamp parameter
- timestamp_part = result[len(expected_base_url):]
- self.assertTrue(timestamp_part.isdigit())
- self.assertGreater(int(timestamp_part), 0)
+ manager = ZoneMinderManager()
+ # Get a client to ensure one is created
+ client1 = manager.zm_client
+ self.assertIsNotNone(client1)
-class TestZoneMinderManagerBooleanConversion(TestCase):
- """Test enum property conversion with custom logic"""
-
- def setUp(self):
- ZoneMinderManager._instance = None
- ZoneMinderManager._lock = threading.Lock()
- self.manager = ZoneMinderManager()
-
- @patch('hi.services.zoneminder.zm_manager.str_to_bool')
- def test_should_add_alarm_events_true(self, mock_str_to_bool):
- """Test should_add_alarm_events returns True when attribute is true"""
- mock_attribute = Mock()
- mock_attribute.value = 'true'
- self.manager._zm_attr_type_to_attribute = {
- ZmAttributeType.ADD_ALARM_EVENTS: mock_attribute
- }
-
- mock_str_to_bool.return_value = True
-
- result = self.manager.should_add_alarm_events
-
- self.assertTrue(result)
- mock_str_to_bool.assert_called_once_with('true')
-
- def test_should_add_alarm_events_false_when_no_attribute(self):
- """Test should_add_alarm_events returns False when no attribute"""
- self.manager._zm_attr_type_to_attribute = {}
+ # Reload configuration
+ manager.reload()
+
+ # Next access should create new client
+ _ = manager.zm_client
+
+ # Should have been called twice (initial + after reload)
+ self.assertEqual(mock_create_client.call_count, 2)
+
+ def test_notify_settings_changed_triggers_reload(self):
+ """notify_settings_changed should trigger reload."""
+ manager = ZoneMinderManager()
+
+ # Register a callback to verify it gets called
+ callback_called = []
- result = self.manager.should_add_alarm_events
+ def test_callback():
+ callback_called.append(True)
+
+ manager.register_change_listener(test_callback)
+
+ # Notify settings changed
+ manager.notify_settings_changed()
+
+ # Callback should have been called
+ self.assertEqual(len(callback_called), 1)
- self.assertFalse(result)
diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.py
index 77c2e800..e949e435 100644
--- a/src/hi/services/zoneminder/zm_manager.py
+++ b/src/hi/services/zoneminder/zm_manager.py
@@ -1,15 +1,16 @@
import logging
+import threading
+from datetime import datetime
from asgiref.sync import sync_to_async
from .pyzm_client.api import ZMApi
from .pyzm_client.helpers.Event import Event as ZmEvent
from .pyzm_client.helpers.Monitor import Monitor as ZmMonitor
from .pyzm_client.helpers.State import State as ZmState
from .pyzm_client.helpers.globals import logger as pyzm_logger
-from threading import Lock
from typing import Dict, List
import hi.apps.common.datetimeproxy as datetimeproxy
-from hi.apps.common.singleton import Singleton
+from hi.apps.common.singleton_manager import SingletonManager
from hi.apps.common.utils import str_to_bool
from hi.integrations.enums import IntegrationHealthStatusType
@@ -25,6 +26,7 @@ from hi.integrations.transient_models import (
)
from hi.integrations.models import Integration, IntegrationAttribute
+from .constants import ZmTimeouts
from .enums import ZmAttributeType
from .zm_client_factory import ZmClientFactory
from .zm_metadata import ZmMetaData
@@ -33,7 +35,7 @@ logger = logging.getLogger(__name__)
pyzm_logger.set_level( 0 ) # pyzm does not use standard 'logging' module. ugh.
-class ZoneMinderManager( Singleton ):
+class ZoneMinderManager( SingletonManager ):
"""
References:
ZM Api code: https://github.com/ZoneMinder/zoneminder/tree/master/web/api/app/Controller
@@ -47,16 +49,16 @@ class ZoneMinderManager( Singleton ):
MONITOR_FUNCTION_SENSOR_PREFIX = 'monitor.function'
ZM_RUN_STATE_SENSOR_INTEGRATION_NAME = 'run.state'
- # ZM monitors and states will not change frequently, so we do not need
- # to query for them at a high frequency.
- #
- STATE_REFRESH_INTERVAL_SECS = 300
- MONITOR_REFRESH_INTERVAL_SECS = 300
+ # Use centralized timeout values from constants
+ STATE_REFRESH_INTERVAL_SECS = ZmTimeouts.STATE_REFRESH_INTERVAL_SECS
+ MONITOR_REFRESH_INTERVAL_SECS = ZmTimeouts.MONITOR_REFRESH_INTERVAL_SECS
def __init_singleton__( self ):
+ super().__init_singleton__() # Initialize _data_lock, _async_data_lock, _was_initialized
self._zm_attr_type_to_attribute = dict()
- self._zm_client = None
self._client_factory = ZmClientFactory()
+ # Thread-local storage for ZMApi clients to avoid session sharing
+ self._thread_local = threading.local()
self._zm_state_list = list()
self._zm_state_timestamp = datetimeproxy.min()
@@ -65,23 +67,22 @@ class ZoneMinderManager( Singleton ):
self._zm_monitor_timestamp = datetimeproxy.min()
self._change_listeners = set()
- self._was_initialized = False
- self._data_lock = Lock()
- # Health status tracking
+ # Health status tracking with enhanced monitoring
self._health_status = IntegrationHealthStatus(
status=IntegrationHealthStatusType.UNKNOWN,
- last_check=datetimeproxy.now()
+ last_check=datetimeproxy.now(),
+ monitor_heartbeat=datetimeproxy.now(),
+ last_api_success=None,
+ api_metrics={
+ 'last_response_time': None,
+ 'consecutive_failures': 0,
+ 'total_calls': 0,
+ 'total_failures': 0,
+ }
)
return
- def ensure_initialized(self):
- if self._was_initialized:
- return
- self.reload()
- self._was_initialized = True
- return
-
def register_change_listener( self, callback ):
if callback not in self._change_listeners:
logger.debug( f'Adding ZM setting change listener from {callback.__module__}' )
@@ -102,40 +103,56 @@ class ZoneMinderManager( Singleton ):
@property
def zm_client(self):
- # Docs: https://pyzm.readthedocs.io/en/latest/
- if not self._zm_client:
- self.reload()
- return self._zm_client
+ """
+ Get thread-local ZMApi client instance.
+
+ Each thread gets its own client with its own requests.Session
+ to avoid thread-safety issues with shared HTTP connections.
+ """
+ # Check if current thread has a client
+ if not hasattr(self._thread_local, 'zm_client') or self._thread_local.zm_client is None:
+ # Ensure we have configuration loaded
+ if not self._was_initialized:
+ self.ensure_initialized()
+
+ # Create new client for this thread
+ if self._zm_attr_type_to_attribute:
+ self._thread_local.zm_client = self.create_zm_client(self._zm_attr_type_to_attribute)
+ logger.debug(f'Created new thread-local ZM client for thread: {threading.current_thread().name}')
+ else:
+ logger.warning('Cannot create ZM client - no attributes configured')
+ self._thread_local.zm_client = None
+ return None
+
+ return self._thread_local.zm_client
- def reload( self ):
- """ Called when integration models are changed (via signals below). """
- logger.debug( 'ZoneMinder manager loading started.' )
- with self._data_lock:
- try:
- self._zm_attr_type_to_attribute = self._load_attributes()
- self._zm_client = self.create_zm_client( self._zm_attr_type_to_attribute )
- self.clear_caches()
- self._update_health_status(IntegrationHealthStatusType.HEALTHY)
- logger.debug( 'ZoneMinder manager loading completed.' )
- except IntegrationDisabledError:
- msg = 'ZoneMinder integration disabled'
- logger.info(msg)
- self._update_health_status( IntegrationHealthStatusType.DISABLED, msg )
- except IntegrationError as e:
- error_msg = f'ZoneMinder integration configuration error: {e}'
- logger.error(error_msg)
- self._update_health_status( IntegrationHealthStatusType.CONFIG_ERROR,
- error_msg)
- except IntegrationAttributeError as e:
- error_msg = f'ZoneMinder integration attribute error: {e}'
- logger.error(error_msg)
- self._update_health_status( IntegrationHealthStatusType.CONFIG_ERROR,
- error_msg )
- except Exception as e:
- error_msg = f'Unexpected error loading ZoneMinder configuration: {e}'
- logger.exception(error_msg)
- self._update_health_status( IntegrationHealthStatusType.TEMPORARY_ERROR,
- error_msg )
+ def _reload_implementation(self):
+ try:
+ self._zm_attr_type_to_attribute = self._load_attributes()
+ # Clear all thread-local clients since configuration changed
+ self._clear_thread_local_clients()
+ self.clear_caches()
+ self._update_health_status(IntegrationHealthStatusType.HEALTHY)
+ logger.debug( 'ZoneMinder manager loading completed.' )
+ except IntegrationDisabledError:
+ msg = 'ZoneMinder integration disabled'
+ logger.info(msg)
+ self._update_health_status( IntegrationHealthStatusType.DISABLED, msg )
+ except IntegrationError as e:
+ error_msg = f'ZoneMinder integration configuration error: {e}'
+ logger.error(error_msg)
+ self._update_health_status( IntegrationHealthStatusType.CONFIG_ERROR,
+ error_msg)
+ except IntegrationAttributeError as e:
+ error_msg = f'ZoneMinder integration attribute error: {e}'
+ logger.error(error_msg)
+ self._update_health_status( IntegrationHealthStatusType.CONFIG_ERROR,
+ error_msg )
+ except Exception as e:
+ error_msg = f'Unexpected error loading ZoneMinder configuration: {e}'
+ logger.exception(error_msg)
+ self._update_health_status( IntegrationHealthStatusType.TEMPORARY_ERROR,
+ error_msg )
return
def clear_caches(self):
@@ -143,6 +160,27 @@ class ZoneMinderManager( Singleton ):
self._zm_monitor_list = list()
return
+ def _clear_thread_local_clients(self):
+ """
+ Clear thread-local client for current thread.
+
+ Note: We can only clear the client for the current thread since
+ threading.local() only exposes data for the current thread.
+ Other threads will get new clients on their next access.
+ """
+ if hasattr(self._thread_local, 'zm_client'):
+ old_client = self._thread_local.zm_client
+ self._thread_local.zm_client = None
+ logger.debug(f'Cleared thread-local ZM client for thread: {threading.current_thread().name}')
+
+ # Clean up the old client's session if possible
+ try:
+ if old_client and hasattr(old_client, 'session'):
+ old_client.session.close()
+ logger.debug('Closed old ZM client session')
+ except Exception as e:
+ logger.debug(f'Error closing old ZM client session: {e}')
+
def _load_attributes(self) -> Dict[ ZmAttributeType, IntegrationAttribute ]:
try:
zm_integration = Integration.objects.get( integration_id = ZmMetaData.integration_id )
@@ -182,9 +220,16 @@ class ZoneMinderManager( Singleton ):
if not self.zm_client:
logger.warning('ZoneMinder client not available - cannot fetch states')
return []
- self._zm_state_list = self.zm_client.states().list()
- self._zm_state_timestamp = datetimeproxy.now()
- logger.debug( f'Fetched ZM states: {[ x.get() for x in self._zm_state_list ]}' )
+
+ # Track API call timing
+ start_time = self._record_api_call_start()
+ try:
+ self._zm_state_list = self.zm_client.states().list()
+ self._zm_state_timestamp = datetimeproxy.now()
+ self._record_api_call_success(start_time)
+ except Exception as e:
+ self._record_api_call_failure(start_time, e)
+ raise
return self._zm_state_list
def get_zm_monitors( self, force_load : bool = False ) -> List[ ZmMonitor ]:
@@ -195,20 +240,36 @@ class ZoneMinderManager( Singleton ):
if not self.zm_client:
logger.warning('ZoneMinder client not available - cannot fetch monitors')
return []
- options = {
- 'force_reload': True, # pyzm caches monitors so need to force api call
- }
- self._zm_monitor_list = self.zm_client.monitors( options ).list()
- self._zm_monitor_timestamp = datetimeproxy.now()
- logger.debug( f'\n\nFetched ZM monitors: {[ x.get() for x in self._zm_monitor_list ]}\n\n' )
-
+
+ # Track API call timing
+ start_time = self._record_api_call_start()
+ try:
+ options = {
+ 'force_reload': True, # pyzm caches monitors so need to force api call
+ }
+ self._zm_monitor_list = self.zm_client.monitors( options ).list()
+ self._zm_monitor_timestamp = datetimeproxy.now()
+ self._record_api_call_success(start_time)
+ except Exception as e:
+ self._record_api_call_failure(start_time, e)
+ raise
+
return self._zm_monitor_list
def get_zm_events( self, options : Dict[ str, str ] ) -> List[ ZmEvent ]:
if not self.zm_client:
logger.warning('ZoneMinder client not available - cannot fetch events')
return []
- return self.zm_client.events( options ).list()
+
+ # Track API call timing for events (this is the most critical API call)
+ start_time = self._record_api_call_start()
+ try:
+ result = self.zm_client.events( options ).list()
+ self._record_api_call_success(start_time)
+ return result
+ except Exception as e:
+ self._record_api_call_failure(start_time, e)
+ raise
async def get_zm_states_async( self, force_load : bool = False ) -> List[ ZmState ]:
"""
@@ -306,18 +367,90 @@ class ZoneMinderManager( Singleton ):
def get_health_status(self) -> IntegrationHealthStatus:
"""Get the current health status of the ZoneMinder integration."""
- return self._health_status
+ # Add on-demand async diagnostics
+ health_status = self._health_status
+ health_status.async_diagnostics = self._get_async_diagnostics()
+ return health_status
+
+ def _get_async_diagnostics(self) -> Dict:
+ """Get async task diagnostics on-demand"""
+ try:
+ from hi.apps.common.asyncio_utils import BackgroundTaskMonitor
+ return BackgroundTaskMonitor.get_background_task_status()
+ except Exception as e:
+ return {'error': f'Failed to get async diagnostics: {e}'}
+
+ def update_monitor_heartbeat(self):
+ """Update the monitor heartbeat timestamp to indicate monitor is alive."""
+ self._health_status.monitor_heartbeat = datetimeproxy.now()
+ logger.debug('Monitor heartbeat updated')
+
+ def get_monitor_status(self) -> Dict:
+ """Get detailed monitor status information for debugging."""
+ # The IntegrationHealthStatus now contains all monitoring data
+ status_dict = self._health_status.to_dict()
+
+ # Add computed heartbeat health check
+ if self._health_status.monitor_heartbeat:
+ now = datetimeproxy.now()
+ heartbeat_age = (now - self._health_status.monitor_heartbeat).total_seconds()
+ status_dict['is_heartbeat_healthy'] = heartbeat_age < ZmTimeouts.MONITOR_HEARTBEAT_TIMEOUT_SECS
+
+ # Add thread-local client information for debugging
+ status_dict['thread_info'] = {
+ 'current_thread': threading.current_thread().name,
+ 'has_thread_local_client': hasattr(self._thread_local, 'zm_client') and self._thread_local.zm_client is not None
+ }
+
+ return status_dict
+
+ def _record_api_call_start(self) -> datetime:
+ """Record the start of an API call for timing purposes."""
+ return datetimeproxy.now()
+
+ def _record_api_call_success(self, start_time: datetime):
+ """Record a successful API call and update metrics."""
+ end_time = datetimeproxy.now()
+ response_time = (end_time - start_time).total_seconds()
+
+ self._health_status.last_api_success = end_time
+ if self._health_status.api_metrics:
+ self._health_status.api_metrics['last_response_time'] = response_time
+ self._health_status.api_metrics['consecutive_failures'] = 0
+ self._health_status.api_metrics['total_calls'] += 1
+
+ # Log performance warnings
+ if response_time > ZmTimeouts.API_RESPONSE_CRITICAL_THRESHOLD_SECS:
+ logger.warning(f'ZoneMinder API call took {response_time:.2f}s (critical threshold: {ZmTimeouts.API_RESPONSE_CRITICAL_THRESHOLD_SECS}s)')
+ elif response_time > ZmTimeouts.API_RESPONSE_WARNING_THRESHOLD_SECS:
+ logger.warning(f'ZoneMinder API call took {response_time:.2f}s (warning threshold: {ZmTimeouts.API_RESPONSE_WARNING_THRESHOLD_SECS}s)')
+
+ def _record_api_call_failure(self, start_time: datetime, error: Exception):
+ """Record a failed API call and update metrics."""
+ end_time = datetimeproxy.now()
+ response_time = (end_time - start_time).total_seconds()
+
+ if self._health_status.api_metrics:
+ self._health_status.api_metrics['consecutive_failures'] += 1
+ self._health_status.api_metrics['total_failures'] += 1
+ self._health_status.api_metrics['total_calls'] += 1
+
+ logger.warning(f'ZoneMinder API call failed after {response_time:.2f}s: {error}')
def _update_health_status(self, status: IntegrationHealthStatusType, error_message: str = None):
"""Update the health status of this integration."""
old_status = self._health_status.status
- # Update health status
+ # Update health status while preserving monitoring data
self._health_status = IntegrationHealthStatus(
status=status,
last_check=datetimeproxy.now(),
error_message=error_message,
- error_count=self._health_status.error_count + (1 if status.is_error else 0)
+ error_count=self._health_status.error_count + (1 if status.is_error else 0),
+ monitor_heartbeat=self._health_status.monitor_heartbeat,
+ last_api_success=self._health_status.last_api_success,
+ api_metrics=self._health_status.api_metrics,
+ async_diagnostics=None # Reset async diagnostics, will be populated on-demand
)
# Log status changes
diff --git a/src/hi/services/zoneminder/zm_mixins.py b/src/hi/services/zoneminder/zm_mixins.py
index f60afaf9..a21bd68e 100644
--- a/src/hi/services/zoneminder/zm_mixins.py
+++ b/src/hi/services/zoneminder/zm_mixins.py
@@ -1,4 +1,3 @@
-from asgiref.sync import sync_to_async
import asyncio
import logging
@@ -19,14 +18,13 @@ class ZoneMinderMixin:
if not hasattr( self, '_zm_manager' ):
self._zm_manager = ZoneMinderManager()
try:
- await asyncio.shield( sync_to_async( self._zm_manager.ensure_initialized )())
-
+ # ensure_initialized_async() already handles thread_sensitive=True internally
+ await asyncio.shield(self._zm_manager.ensure_initialized_async())
except asyncio.CancelledError:
- logger.warning( 'ZM init sync_to_async() was cancelled! Handling gracefully.')
+ logger.warning( 'ZM init ensure_initialized_async() was cancelled! Handling gracefully.')
return None
-
except Exception as e:
- logger.warning( f'ZM init sync_to_async() exception! Handling gracefully. ({e})' )
+ logger.warning( f'ZM init ensure_initialized_async() exception! Handling gracefully. ({e})' )
return None
return self._zm_manager
diff --git a/src/hi/settings/local.py b/src/hi/settings/local.py
index e60d8860..790873a4 100644
--- a/src/hi/settings/local.py
+++ b/src/hi/settings/local.py
@@ -36,6 +36,7 @@ LOGGING = {
'hi': {
'handlers': ['console' ],
'level': 'INFO',
+ 'propagate': False,
},
},
}