Skip to content

Home Information - Your home, your data, organized.

Python

FInal (hopefully_ solution to getting background threads running.

Anthony Cassandra3e0917d12a5d
diff --git a/Dockerfile b/Dockerfile
index 1e73a218..e5133308 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,7 +1,7 @@
FROM python:3.11
RUN apt-get update \
- && apt-get install -y --no-install-recommends supervisor nginx redis-server \
+ && apt-get install -y --no-install-recommends supervisor nginx redis-server redis-tools \
&& mkdir -p /var/log/supervisor \
&& mkdir -p /etc/supervisor/conf.d \
&& rm -rf /var/lib/apt/lists/* \
@@ -25,8 +25,8 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
COPY src/hi/requirements/base.txt /src/requirements.txt
RUN pip install --no-cache-dir --root-user-action=ignore -r requirements.txt
-COPY packaging/supervisor-interface.conf /etc/supervisor/conf.d/waa-interface.conf
-COPY packaging/nginx-interface.conf /etc/nginx/sites-available/default
+COPY packaging/docker_supervisord.conf /etc/supervisor/conf.d/hi.conf
+COPY packaging/docker_nginx.conf /etc/nginx/sites-available/default
COPY packaging/docker_entrypoint.sh /src/entrypoint.sh
RUN chmod +x /src/entrypoint.sh
diff --git a/Makefile b/Makefile
index 773ebe36..7b387233 100644
--- a/Makefile
+++ b/Makefile
@@ -13,6 +13,9 @@ docker-build: Dockerfile
--tag hi:latest .
docker-run: .private/env/local.dev Dockerfile
+ ./deploy/run_container.sh -bg
+
+docker-run-fg: .private/env/local.dev Dockerfile
./deploy/run_container.sh
docker-stop:
diff --git a/packaging/docker_entrypoint.sh b/packaging/docker_entrypoint.sh
index e9aca9aa..c34e8239 100644
--- a/packaging/docker_entrypoint.sh
+++ b/packaging/docker_entrypoint.sh
@@ -1,9 +1,8 @@
#!/bin/bash
+echo "Initial Django admin initialization."
cd /src
-echo "Starting initialization..."
-
echo "Collecting static files..."
python manage.py collectstatic --noinput
diff --git a/packaging/nginx-interface.conf b/packaging/docker_nginx.conf
similarity index 100%
rename from packaging/nginx-interface.conf
rename to packaging/docker_nginx.conf
diff --git a/packaging/supervisor-interface.conf b/packaging/docker_supervisord.conf
similarity index 94%
rename from packaging/supervisor-interface.conf
rename to packaging/docker_supervisord.conf
index 056d429c..d6efe12f 100644
--- a/packaging/supervisor-interface.conf
+++ b/packaging/docker_supervisord.conf
@@ -8,6 +8,7 @@ autostart=true
autorestart=true
stdout_logfile=/var/log/supervisor/redis.log
stderr_logfile=/var/log/supervisor/redis_err.log
+priority=10
[program:wsgi_gunicorn]
@@ -21,6 +22,7 @@ stopsignal=KILL
stopasgroup=true
autostart=true
autorestart=true
+priority=20
[program:nginx]
user=root
@@ -32,3 +34,4 @@ stdout_logfile_maxbytes=0
redirect_stderr=true
autostart=true
autorestart=true
+priority=30
diff --git a/src/bin/docker-gunicorn.conf.py b/src/bin/docker-gunicorn.conf.py
new file mode 100644
index 00000000..ce54865a
--- /dev/null
+++ b/src/bin/docker-gunicorn.conf.py
@@ -0,0 +1,10 @@
+def post_worker_init( worker ):
+ """Start all background processes.
+
+ Note that launching these needs to happen elsewhere for the
+ non-gunicorn executions, e.g., "./manage.py runserver". See the
+ AppConfig.ready() function of these app modules for this other case.
+ """
+ from hi.background_tasks import HiBackgroundTaskHelper
+ HiBackgroundTaskHelper.start_background_tasks()
+ return
diff --git a/src/bin/docker-start-gunicorn.sh b/src/bin/docker-start-gunicorn.sh
index 553d3078..f763680c 100755
--- a/src/bin/docker-start-gunicorn.sh
+++ b/src/bin/docker-start-gunicorn.sh
@@ -1,10 +1,37 @@
#!/bin/sh
-NUM_WORKERS=3
+# NUM_WORKERS must remain "1" until refactored for multiple processes to
+# share the state of the background managers and monitors. Else too much
+# API polling and processes having inconsistent states.
+
+NUM_WORKERS=1
NUM_THREADS=3
BINDARG=unix:/var/run/gunicorn.sock
+check_redis() {
+ echo "Checking if Redis is ready..."
+
+ REDIS_RETRY_LIMIT=10
+ REDIS_RETRY_INTERVAL=1
+ counter=0
+
+ until redis-cli -h localhost ping | grep -q PONG; do
+ echo "Waiting for Redis to be ready... ($counter seconds elapsed)"
+ sleep $REDIS_RETRY_INTERVAL
+ counter=$((counter+REDIS_RETRY_INTERVAL))
+ if [ "$counter" -ge "$REDIS_RETRY_LIMIT" ]; then
+ echo ""
+ echo "** ERROR ** Redis did not start within $REDIS_RETRY_LIMIT seconds. Exiting."
+ echo ""
+ exit 1
+ fi
+ done
+
+ echo "Redis is ready."
+}
+
exec gunicorn hi.wsgi:application \
+ -c /src/bin/docker-gunicorn.conf.py \
--name gunicorn \
--workers $NUM_WORKERS \
--threads $NUM_THREADS \
@@ -18,6 +45,7 @@ exec gunicorn hi.wsgi:application \
#BINDARG=unix:/var/run/gunicorn.sock
#
#exec gunicorn hi.asgi:application \
+# -c /src/bin/docker-gunicorn.conf.py \
# --name gunicorn \
# --workers $NUM_WORKERS \
# --worker-class uvicorn.workers.UvicornWorker \
diff --git a/src/hi/apps/common/asyncio_utils.py b/src/hi/apps/common/asyncio_utils.py
index 0d896693..86f8445a 100644
--- a/src/hi/apps/common/asyncio_utils.py
+++ b/src/hi/apps/common/asyncio_utils.py
@@ -8,9 +8,8 @@ def start_background_event_loop( task_function ):
:param task_function: Async function to be executed inside the thread.
"""
-
def run_background_task_in_thread():
-
+
async def run_background_task():
await task_function()
return
@@ -21,7 +20,7 @@ def start_background_event_loop( task_function ):
background_loop.call_soon_threadsafe( asyncio.create_task, run_background_task() )
background_loop.run_forever()
return
-
+
background_thread = Thread( target = run_background_task_in_thread )
background_thread.daemon = True
background_thread.start()
diff --git a/src/hi/apps/common/datetimeproxy.py b/src/hi/apps/common/datetimeproxy.py
index 9ae9f7ff..9d9da90d 100644
--- a/src/hi/apps/common/datetimeproxy.py
+++ b/src/hi/apps/common/datetimeproxy.py
@@ -408,3 +408,7 @@ def is_time_of_day_in_interval( time_of_day_str : str,
target_datetime_tz = timezone.localize( datetime.datetime.combine( today, target_time ) )
return bool(( target_datetime_tz > start_datetime_tz ) and ( target_datetime_tz <= end_datetime_tz ))
+
+
+def is_valid_timezone_name( tz_name : str ) -> bool:
+ return tz_name in pytz.all_timezones_set
diff --git a/src/hi/apps/common/singleton.py b/src/hi/apps/common/singleton.py
index 73b29941..0856ae8a 100644
--- a/src/hi/apps/common/singleton.py
+++ b/src/hi/apps/common/singleton.py
@@ -11,15 +11,9 @@ class Singleton:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
- cls._instance.__init_singleton_internal__()
+ cls._instance.__init_singleton__()
return cls._instance
- def __init_singleton_internal__(self):
- if not self._initialized:
- self._initialized = True
- self.__init_singleton__()
- return
-
def __init_singleton__(self):
""" Subclasses can override this if needed. """
return
diff --git a/src/hi/apps/config/settings_manager.py b/src/hi/apps/config/settings_manager.py
index ae477ee6..cce2cad8 100644
--- a/src/hi/apps/config/settings_manager.py
+++ b/src/hi/apps/config/settings_manager.py
@@ -190,7 +190,7 @@ _thread_local = local()
def do_settings_manager_reload():
logger.debug( 'Reloading SettingsManager from model changes.')
settings_manager = SettingsManager()
- settings_manager = settings_manager.ensure_initialized()
+ settings_manager.ensure_initialized()
settings_manager.reload()
_thread_local.reload_registered = False
return
diff --git a/src/hi/apps/event/event_manager.py b/src/hi/apps/event/event_manager.py
index dd106c7d..c98f5bee 100644
--- a/src/hi/apps/event/event_manager.py
+++ b/src/hi/apps/event/event_manager.py
@@ -80,7 +80,7 @@ class EventManager( Singleton, AlertMixin, ControllerMixin ):
self._recent_transitions.extend( entity_state_transition_list )
self._purge_old_transitions()
- new_event_list = self._get_new_events()
+ new_event_list = await self._get_new_events()
logger.debug( f'New events found: {new_event_list}' )
@@ -88,15 +88,16 @@ class EventManager( Singleton, AlertMixin, ControllerMixin ):
await self._add_to_event_history( event_list = new_event_list )
return
- def _get_new_events( self ):
+ async def _get_new_events( self ):
if self._event_definition_reload_needed:
- self.reload()
+ await sync_to_async( self.reload, thread_sensitive = True )()
+
with self._event_definitions_lock:
new_event_list = list()
for event_definition in self._event_definitions:
- if self._has_recent_event( event_definition ):
+ if await self._has_recent_event( event_definition ):
continue
- event = self._create_event_if_detected( event_definition )
+ event = await self._create_event_if_detected( event_definition )
if not event:
continue
self._recent_events[event_definition.id] = event
@@ -105,14 +106,14 @@ class EventManager( Singleton, AlertMixin, ControllerMixin ):
return new_event_list
- def _has_recent_event( self, event_definition : EventDefinition ) -> bool:
+ async 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 )
- def _create_event_if_detected( self, event_definition : EventDefinition ) -> bool:
+ async def _create_event_if_detected( self, event_definition : EventDefinition ) -> bool:
if not event_definition.event_clauses.exists():
return False
@@ -140,6 +141,7 @@ class EventManager( Singleton, AlertMixin, ControllerMixin ):
event_definition = event_definition,
sensor_response_list = sensor_response_list,
)
+ return event
def _purge_old_transitions( self ):
current_timestamp = datetimeproxy.now()
diff --git a/src/hi/apps/monitor/apps.py b/src/hi/apps/monitor/apps.py
index d77c66fe..842fe0c9 100644
--- a/src/hi/apps/monitor/apps.py
+++ b/src/hi/apps/monitor/apps.py
@@ -1,27 +1,30 @@
+import os
+import sys
from django.apps import AppConfig
-from django.core.checks import Error, register
-
-from hi.apps.common.asyncio_utils import start_background_event_loop
class MonitorConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "hi.apps.monitor"
+ def ready(self):
+ from hi.background_tasks import HiBackgroundTaskHelper
+
+ # Notes:
+ # - This method does not run in a production-like environment using gunicorn.
+ # - When it is called, it is often called multiple times during Django initialization.
+ # - Django seem to be suing different processes on each invocation.
+
+ if os.environ.get('RUN_MAIN') != 'true': # Prevents duplicate execution in `runserver`
+ return
+
+ # The responsibility for replicating the logic below falls to
+ # gunicorn when it is being used (via its post_fork() config file).
+ #
+ if (( "gunicorn" in os.environ.get("SERVER_SOFTWARE", ""))
+ or ( "gunicorn" in sys.argv[0] )):
+ return
-@register()
-def check_start_background_tasks( app_configs, **kwargs ):
- """Start background tasks after all system checks have passed."""
- from hi.apps.monitor.monitor_manager import AppMonitorManager
- try:
- start_background_event_loop( task_function = AppMonitorManager().initialize )
- except Exception as e:
- return [
- Error(
- "Failed to start background tasks.",
- hint=f"Error: {e}",
- obj='background_tasks',
- id='hi.apps.monitor',
- )
- ]
- return []
+ HiBackgroundTaskHelper.start_background_tasks_delayed()
+ return
+
diff --git a/src/hi/apps/monitor/monitor_manager.py b/src/hi/apps/monitor/monitor_manager.py
index 2d1fe52d..5f3457c2 100644
--- a/src/hi/apps/monitor/monitor_manager.py
+++ b/src/hi/apps/monitor/monitor_manager.py
@@ -81,4 +81,3 @@ class AppMonitorManager( Singleton ):
continue
return periodic_monitor_class_list
-
diff --git a/src/hi/background_tasks.py b/src/hi/background_tasks.py
new file mode 100644
index 00000000..58ecdd4b
--- /dev/null
+++ b/src/hi/background_tasks.py
@@ -0,0 +1,60 @@
+import logging
+import os
+from django.core.signals import request_started
+
+from hi.apps.common.asyncio_utils import start_background_event_loop
+from hi.apps.monitor.monitor_manager import AppMonitorManager
+from hi.integrations.integration_manager import IntegrationManager
+
+logger = logging.getLogger(__name__)
+
+
+class HiBackgroundTaskHelper:
+
+ _request_started_connect = False
+ _background_requests_started = False
+
+ @classmethod
+ def start_background_tasks_delayed(cls):
+ """
+ Delay starting background tasks until first user request. Adds latency,
+ but the most reliable way to ensure Dajngo is fully configure. You
+ can't launch these in APpConfig.ready() as Django is not actualy
+ quite "ready" and new threads will fail. You cannot add a delay
+ with time.sleep() because that also interferes with Django's
+ initialization process. Deferring until the first request is the
+ lesser of all the evils.
+ """
+ if cls.is_management_command():
+ return
+ if cls._request_started_connect:
+ return
+ request_started.connect( lambda sender, **kwargs: cls.start_background_tasks() )
+ cls._request_started_connect = True
+ return
+
+ @classmethod
+ def start_background_tasks(cls):
+ if cls.is_management_command():
+ return
+
+ if cls._request_started_connect:
+ request_started.disconnect( lambda sender, **kwargs: cls.start_background_tasks() )
+ cls._request_started_connect = False
+
+ if cls._background_requests_started:
+ return
+
+ logger.info( 'Starting AppMonitorManager ...' )
+ start_background_event_loop( task_function = AppMonitorManager().initialize )
+
+ logger.info( 'Starting IntegrationManager ...' )
+ start_background_event_loop( task_function = IntegrationManager().initialize )
+
+ cls._background_requests_started = True
+ return
+
+ @classmethod
+ def is_management_command(cls) -> bool:
+ return bool( os.environ.get('DJANGO_MANAGEMENT_COMMAND') is not None )
+
diff --git a/src/hi/integrations/apps.py b/src/hi/integrations/apps.py
index 9e43c76d..9ed5fd56 100644
--- a/src/hi/integrations/apps.py
+++ b/src/hi/integrations/apps.py
@@ -1,28 +1,31 @@
+import os
+import sys
from django.apps import AppConfig
-from django.core.checks import Error, register
-from hi.apps.common.asyncio_utils import start_background_event_loop
-
-class CoreConfig(AppConfig):
+class IntegrationsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "hi.integrations"
+ def ready(self):
+ from hi.background_tasks import HiBackgroundTaskHelper
+
+ # Notes:
+ # - This method does not run in a production-like environment using gunicorn.
+ # - When it is called, it is often called multiple times during Django initialization.
+ # - Django seem to be suing different processes on each invocation.
+
+ if os.environ.get('RUN_MAIN') != 'true': # Prevents duplicate execution in `runserver`
+ return
+
+ # The responsibility for replicating the logic below falls to
+ # gunicorn when it is being used (via its post_fork() config file).
+ #
+ if (( "gunicorn" in os.environ.get("SERVER_SOFTWARE", ""))
+ or ( "gunicorn" in sys.argv[0] )):
+ return
-@register()
-def check_start_background_tasks( app_configs, **kwargs ):
- """Start background tasks after all system checks have passed."""
- from hi.integrations.integration_manager import IntegrationManager
- try:
- start_background_event_loop( task_function = IntegrationManager().initialize )
- except Exception as e:
- return [
- Error(
- "Failed to start integration background threrad or tasks.",
- hint = f"Error: {e}",
- obj = 'start_background_thread',
- id = 'hi.apps.integraton',
- )
- ]
- return []
+ HiBackgroundTaskHelper.start_background_tasks_delayed()
+ return
+
diff --git a/src/hi/integrations/integration_manager.py b/src/hi/integrations/integration_manager.py
index 6c9f6957..53309d19 100644
--- a/src/hi/integrations/integration_manager.py
+++ b/src/hi/integrations/integration_manager.py
@@ -26,6 +26,9 @@ logger = logging.getLogger(__name__)
class IntegrationManager( Singleton ):
+ def __new__(cls):
+ return super().__new__(cls)
+
def __init_singleton__( self ):
self._integration_data_map : Dict[ str, IntegrationData ] = dict()
self._monitor_map = dict()
@@ -273,4 +276,3 @@ class IntegrationManager( Singleton ):
integration_data.integration.save()
self._stop_integration_monitor( integration_data = integration_data )
return
-
diff --git a/src/hi/integrations/models.py b/src/hi/integrations/models.py
index 8388a85f..cb7e0083 100644
--- a/src/hi/integrations/models.py
+++ b/src/hi/integrations/models.py
@@ -101,6 +101,3 @@ class IntegrationKeyModel( models.Model ):
self.integration_id = integration_key.integration_id
self.integration_name = integration_key.integration_name
return
-
-
-
diff --git a/src/hi/services/hass/monitors.py b/src/hi/services/hass/monitors.py
index 37aeac57..9bdf6592 100644
--- a/src/hi/services/hass/monitors.py
+++ b/src/hi/services/hass/monitors.py
@@ -1,3 +1,4 @@
+from asgiref.sync import async_to_sync
import logging
import hi.apps.common.datetimeproxy as datetimeproxy
@@ -13,7 +14,7 @@ logger = logging.getLogger(__name__)
class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):
- HASS_POLLING_INTERVAL_SECS = 10
+ HASS_POLLING_INTERVAL_SECS = 2
def __init__( self ):
super().__init__(
@@ -39,8 +40,12 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):
async def do_work(self):
if not self._was_initialized:
await self._initialize()
-
- id_to_hass_state_map = self.hass_manager().fetch_hass_states_from_api( verbose = False )
+
+ hass_manager = await self.hass_manager_async()
+ if not hass_manager:
+ return
+
+ id_to_hass_state_map = hass_manager.fetch_hass_states_from_api( verbose = False )
logger.debug( f'Fetched {len(id_to_hass_state_map)} HAss States' )
current_datetime = datetimeproxy.now()
diff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.py
index 9e6846ac..59e918bd 100644
--- a/src/hi/services/zoneminder/monitors.py
+++ b/src/hi/services/zoneminder/monitors.py
@@ -21,7 +21,7 @@ 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 = 10
+ ZONEMINDER_POLLING_INTERVAL_SECS = 4
CACHING_DISABLED = True
diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.py
index 0c78a2e2..91176aef 100644
--- a/src/hi/services/zoneminder/zm_manager.py
+++ b/src/hi/services/zoneminder/zm_manager.py
@@ -237,8 +237,13 @@ class ZoneMinderManager( Singleton ):
integration_key_str = str(integration_key),
).first()
if integration_attribute:
- return integration_attribute.value
- logger.error( 'ZoneMinder integration is not implemented.' )
+ tz_name = integration_attribute.value
+ if datetimeproxy.is_valid_timezone_name( tz_name = tz_name ):
+ return tz_name
+ else:
+ logger.warning( f'ZoneMinder timezone setting is invalid: {tz_name}' )
+
+ logger.error( 'ZoneMinder timezone name is not available.' )
except IntegrationAttribute.DoesNotExist:
logger.error( 'ZoneMinder timezone not found.' )
diff --git a/src/hi/simulator/apps.py b/src/hi/simulator/apps.py
index 21003f83..886df656 100644
--- a/src/hi/simulator/apps.py
+++ b/src/hi/simulator/apps.py
@@ -1,27 +1,35 @@
+import os
+import sys
from django.apps import AppConfig
-from django.core.checks import Error, register
-
-from hi.apps.common.asyncio_utils import start_background_event_loop
class SimulatorConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "hi.simulator"
+ def ready(self):
+ import time
+ from hi.apps.common.asyncio_utils import start_background_event_loop
+ from hi.simulator.simulator_manager import SimulatorManager
+
+ # Notes:
+ # - This method does not run in a production-like environment using gunicorn.
+ # - When it is called, it is often called multiple times during Django initialization.
+ # - Django seem to be suing different processes on each invocation.
+
+ if os.environ.get('RUN_MAIN') != 'true': # Prevents duplicate execution in `runserver`
+ return
+
+ # The responsibility for replicating the logic below falls to
+ # gunicorn when it is being used (via its post_fork() config file).
+ #
+ # However, the simulator is not currently set up for anything but
+ # runserver execution.
+ #
+ if (( "gunicorn" in os.environ.get("SERVER_SOFTWARE", ""))
+ or ( "gunicorn" in sys.argv[0] )):
+ return
-@register()
-def check_start_background_tasks( app_configs, **kwargs ):
- """Start background tasks after all system checks have passed."""
- from hi.simulator.simulator_manager import SimulatorManager
- try:
+ time.sleep(1)
start_background_event_loop( task_function = SimulatorManager().initialize )
- except Exception as e:
- return [
- Error(
- "Failed to start integration background threrad or tasks.",
- hint = f"Error: {e}",
- obj = 'start_background_thread',
- id = 'hi.simulator',
- )
- ]
- return []
+ return
diff --git a/src/hi/simulator/simulator_manager.py b/src/hi/simulator/simulator_manager.py
index 66740fe7..7c5706db 100644
--- a/src/hi/simulator/simulator_manager.py
+++ b/src/hi/simulator/simulator_manager.py
@@ -238,3 +238,5 @@ class SimulatorManager( Singleton ):
continue
return
+
+