🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Fix #239: harden backend against stale-DB gevent freeze
Omega (QA)7cc8f3f1cc31
diff --git a/Dockerfile b/Dockerfileindex 34f95fd..6fab8a9 100644--- a/Dockerfile+++ b/Dockerfile@@ -94,9 +94,11 @@ ENV PYTHONUNBUFFERED=1 \# Clean default nginx siteRUN rm -f /etc/nginx/sites-enabled/default-# Optimized health check+# Optimized health check - hits the backend's /api/health (which verifies DB+# connectivity) so a frozen backend is detected instead of the container+# reporting healthy via nginx alone (see issue #239).HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \- CMD curl -f http://localhost/api/health 2>/dev/null || curl -f http://localhost/ || exit 1+ CMD curl -f http://localhost/api/health || exit 1# Exposed portEXPOSE 80diff --git a/backend/__init__.py b/backend/__init__.pyindex c5f99bc..0e5442f 100644--- a/backend/__init__.py+++ b/backend/__init__.py@@ -2,7 +2,7 @@import osimport loggingimport psycopg2.errors-from flask import Flask+from flask import Flask, jsonifyfrom werkzeug.middleware.proxy_fix import ProxyFixlogger = logging.getLogger(__name__)@@ -215,5 +215,28 @@ def create_app(config_name=None):# Continue without notifications - the app can still functionlogger.info("Application factory completed successfully")-++ @app.route('/api/health', methods=['GET'])+ def health_check():+ """Unauthenticated health check for Docker HEALTHCHECK / load balancers.++ Verifies the app can actually reach the database with a short timeout.+ Returns 503 when the DB is unreachable so a frozen backend is detected+ instead of the container reporting healthy (see issue #239).+ """+ try:+ from .db_handler import get_db_connection, release_db_connection+ conn = get_db_connection()+ try:+ with conn.cursor() as cur:+ cur.execute("SET LOCAL statement_timeout = '5s'")+ cur.execute("SELECT 1")+ cur.fetchone()+ finally:+ release_db_connection(conn)+ return jsonify({"status": "ok"}), 200+ except Exception as e:+ logger.warning(f"Health check failed: {e}")+ return jsonify({"status": "error"}), 503+return appdiff --git a/backend/db_handler.py b/backend/db_handler.pyindex 86f3c2f..ea0ef4f 100644--- a/backend/db_handler.py+++ b/backend/db_handler.py@@ -66,7 +66,16 @@ def init_db_pool(max_retries=5, retry_delay=5):password=DB_PASSWORD,# Memory optimization settingsconnect_timeout=10, # Connection timeout- application_name='warracker_optimized' # Identify connections+ application_name='warracker_optimized', # Identify connections+ # Resilience against stale/dead connections (see issue #239):+ # - statement_timeout bounds any single query so a greenlet can+ # never block inside libpq forever on a dead connection+ # - TCP keepalives let the OS detect a dead peer on idle conns+ options='-c statement_timeout=30000',+ keepalives=1,+ keepalives_idle=30,+ keepalives_interval=10,+ keepalives_count=5,)logger.info("[DB_HANDLER] Database connection pool initialized successfully.")pool_pid = current_piddiff --git a/backend/gunicorn_config.py b/backend/gunicorn_config.pyindex 59e9ab5..6e75ed2 100644--- a/backend/gunicorn_config.py+++ b/backend/gunicorn_config.py@@ -20,6 +20,14 @@ if memory_mode in ('optimized', 'performance'):print("✅ Early gevent monkey patch applied for SSL compatibility.")except ImportError:print("⚠️ Gevent not found, but gevent workers will be requested. This may cause issues.")+ # Make psycopg2 cooperate with the gevent hub so a blocked socket read+ # yields to the event loop instead of freezing the worker (see issue #239)+ try:+ from psycogreen.gevent import patch_psycopg+ patch_psycopg()+ print("✅ psycogreen gevent patch applied for psycopg2.")+ except ImportError:+ print("⚠️ psycogreen not installed; psycopg2 will block gevent workers on slow queries.")import multiprocessingdiff --git a/backend/requirements.txt b/backend/requirements.txtindex e3520ab..03f5f37 100644--- a/backend/requirements.txt+++ b/backend/requirements.txt@@ -12,6 +12,7 @@ python-dateutil==2.9.0.post0Authlib==1.7.2requests==2.34.2gevent==24.11.1+psycogreen==1.0.2setuptools==82.0.1apprise==1.10.0Flask-Babel==4.0.0