From 9b2ebf169bea3f99cce1879128b78c056fa6a561 Mon Sep 17 00:00:00 2001 From: SergeantPanda Date: Thu, 16 Oct 2025 14:22:19 -0500 Subject: [PATCH] Better database connection cleanup. --- apps/proxy/config.py | 15 ++++++++------- apps/proxy/ts_proxy/services/channel_service.py | 9 +++++++++ apps/proxy/ts_proxy/stream_manager.py | 9 +++++++++ dispatcharr/celery.py | 14 +++++++++++--- 4 files changed, 37 insertions(+), 10 deletions(-) diff --git a/apps/proxy/config.py b/apps/proxy/config.py index c3d0cc27..74bfc61f 100644 --- a/apps/proxy/config.py +++ b/apps/proxy/config.py @@ -33,14 +33,8 @@ class BaseConfig: settings = CoreSettings.get_proxy_settings() cls._proxy_settings_cache = settings cls._proxy_settings_cache_time = now - - # Close the connection after reading settings to avoid keeping it open - try: - connection.close() - except Exception: - pass - return settings + except Exception: # Return defaults if database query fails return { @@ -50,6 +44,13 @@ class BaseConfig: "channel_shutdown_delay": 0, "channel_init_grace_period": 5, } + + finally: + # Always close the connection after reading settings + try: + connection.close() + except Exception: + pass @classmethod def get_redis_chunk_ttl(cls): diff --git a/apps/proxy/ts_proxy/services/channel_service.py b/apps/proxy/ts_proxy/services/channel_service.py index ac8f3a10..551e2d27 100644 --- a/apps/proxy/ts_proxy/services/channel_service.py +++ b/apps/proxy/ts_proxy/services/channel_service.py @@ -597,6 +597,8 @@ class ChannelService: @staticmethod def _update_stream_stats_in_db(stream_id, **stats): """Update stream stats in database""" + from django.db import connection + try: from apps.channels.models import Stream from django.utils import timezone @@ -622,6 +624,13 @@ class ChannelService: except Exception as e: logger.error(f"Error updating stream stats in database for stream {stream_id}: {e}") return False + + finally: + # Always close database connection after update + try: + connection.close() + except Exception: + pass # Helper methods for Redis operations diff --git a/apps/proxy/ts_proxy/stream_manager.py b/apps/proxy/ts_proxy/stream_manager.py index e3620886..99ae8027 100644 --- a/apps/proxy/ts_proxy/stream_manager.py +++ b/apps/proxy/ts_proxy/stream_manager.py @@ -930,6 +930,7 @@ class StreamManager: # Import both models for proper resource management from apps.channels.models import Stream, Channel + from django.db import connection # Update stream profile if we're switching streams if self.current_stream_id and stream_id and self.current_stream_id != stream_id: @@ -947,8 +948,16 @@ class StreamManager: logger.debug(f"Updated m3u profile for channel {self.channel_id} to use profile from stream {stream_id}") else: logger.warning(f"Failed to update stream profile for channel {self.channel_id}") + except Exception as e: logger.error(f"Error updating stream profile for channel {self.channel_id}: {e}") + + finally: + # Always close database connection after profile update + try: + connection.close() + except Exception: + pass # CRITICAL: Set a flag to prevent immediate reconnection with old URL self.url_switching = True diff --git a/dispatcharr/celery.py b/dispatcharr/celery.py index 98c6210b..c845dafe 100644 --- a/dispatcharr/celery.py +++ b/dispatcharr/celery.py @@ -50,13 +50,21 @@ app.conf.update( ) # Add memory cleanup after task completion -#@task_postrun.connect # Use the imported signal +@task_postrun.connect # Use the imported signal def cleanup_task_memory(**kwargs): - """Clean up memory after each task completes""" + """Clean up memory and database connections after each task completes""" + from django.db import connection + # Get task name from kwargs task_name = kwargs.get('task').name if kwargs.get('task') else '' - # Only run cleanup for memory-intensive tasks + # Close database connection for this Celery worker process + try: + connection.close() + except Exception: + pass + + # Only run memory cleanup for memory-intensive tasks memory_intensive_tasks = [ 'apps.m3u.tasks.refresh_single_m3u_account', 'apps.m3u.tasks.refresh_m3u_accounts',