Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

fix: stop status checks failing with "database is locked" (#557)

Pouzor - Rémy Jardient6a9777648a70
diff --git a/backend/app/core/scheduler.py b/backend/app/core/scheduler.py
index c47bed0..9da5625 100644
--- a/backend/app/core/scheduler.py
+++ b/backend/app/core/scheduler.py
@@ -3,7 +3,7 @@ import asyncio
import logging
from collections.abc import Awaitable, Callable
from datetime import datetime, timezone
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, NamedTuple
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from sqlalchemy import select
@@ -32,44 +32,79 @@ async def _nodes_by_device(db: AsyncSession) -> dict[str, list[str]]:
return out
+class _CheckOutcome(NamedTuple):
+ device_id: str
+ status: str
+ response_time_ms: int | None
+ checked_at: datetime
+
+
async def _check_single_device(
device_id: str,
node_ids: list[str],
check_method: str,
check_target: str | None,
ip: str | None,
-) -> tuple[str, dict[str, object] | None]:
- """Run a single device check; returns (device_id, result_or_None).
+) -> _CheckOutcome | None:
+ """Probe one device and broadcast the result; returns None if the probe failed.
Accepts plain scalars — not an ORM object — so there is no risk of
DetachedInstanceError when the originating session has already closed.
+
+ It does not write: `_save_check_outcomes` persists the whole cycle at once.
+ The broadcast goes out here, as soon as the probe answers, so a canvas is
+ not kept waiting on the slowest device or on the database.
"""
from app.api.routes.status import broadcast_status # avoid circular import
try:
check_result = await check_node(check_method, check_target, ip)
- raw_ms = check_result["response_time_ms"]
- response_ms = raw_ms if isinstance(raw_ms, int) else None
- now = datetime.now(timezone.utc)
- async with AsyncSessionLocal() as db:
- device = await db.get(InventoryDevice, device_id)
- if device:
- device.status_live = str(check_result["status"])
- device.response_time_ms = response_ms
- if check_result["status"] == "online":
- device.last_seen = now
- await db.commit()
+ except Exception as exc:
+ logger.error("Status check failed for device %s: %s", device_id, exc)
+ return None
+ raw_ms = check_result["response_time_ms"]
+ outcome = _CheckOutcome(
+ device_id=device_id,
+ status=str(check_result["status"]),
+ response_time_ms=raw_ms if isinstance(raw_ms, int) else None,
+ checked_at=datetime.now(timezone.utc),
+ )
+ try:
await broadcast_status(
device_id=device_id,
node_ids=node_ids,
- status=str(check_result["status"]),
- checked_at=now.isoformat(),
- response_time_ms=response_ms,
+ status=outcome.status,
+ checked_at=outcome.checked_at.isoformat(),
+ response_time_ms=outcome.response_time_ms,
)
- return device_id, check_result
except Exception as exc:
- logger.error("Status check failed for device %s: %s", device_id, exc)
- return device_id, None
+ logger.error("Status broadcast failed for device %s: %s", device_id, exc)
+ return outcome
+
+
+async def _save_check_outcomes(outcomes: list[_CheckOutcome]) -> None:
+ """Persist a whole status cycle in one write transaction.
+
+ One commit per device meant as many writers queueing on SQLite's single
+ write lock as there are devices, and the ones at the back of the queue gave
+ up with "database is locked" (#539). A failure here costs the stored state
+ of one cycle, never the live one: the broadcasts have already gone out.
+ """
+ by_id = {o.device_id: o for o in outcomes}
+ try:
+ async with AsyncSessionLocal() as db:
+ devices = (
+ await db.execute(select(InventoryDevice).where(InventoryDevice.id.in_(by_id)))
+ ).scalars().all()
+ for device in devices:
+ outcome = by_id[device.id]
+ device.status_live = outcome.status
+ device.response_time_ms = outcome.response_time_ms
+ if outcome.status == "online":
+ device.last_seen = outcome.checked_at
+ await db.commit()
+ except Exception as exc:
+ logger.error("Could not save the status of %d device(s): %s", len(outcomes), exc)
async def _run_status_checks() -> None:
@@ -108,10 +143,13 @@ async def _run_status_checks() -> None:
if not checkable:
return
- await asyncio.gather(*[
+ results = await asyncio.gather(*[
_check_single_device(device_id, node_ids, method, target, ip)
for device_id, node_ids, method, target, ip in checkable
])
+ outcomes = [r for r in results if r is not None]
+ if outcomes:
+ await _save_check_outcomes(outcomes)
def _node_host(ip: str | None, hostname: str | None) -> str | None:
diff --git a/backend/app/db/database.py b/backend/app/db/database.py
index 986359c..a46833d 100644
--- a/backend/app/db/database.py
+++ b/backend/app/db/database.py
@@ -9,7 +9,13 @@ from pathlib import Path
from typing import Any
from sqlalchemy.exc import IntegrityError, OperationalError
-from sqlalchemy.ext.asyncio import AsyncConnection, AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.ext.asyncio import (
+ AsyncConnection,
+ AsyncEngine,
+ AsyncSession,
+ async_sessionmaker,
+ create_async_engine,
+)
from sqlalchemy.orm import DeclarativeBase
from app.core.config import APP_VERSION, settings
@@ -93,10 +99,21 @@ async def _try_migrate(conn: AsyncConnection, sql: str, *, label: str) -> None:
# Ensure the data directory exists before SQLite tries to open the file
Path(settings.sqlite_path).parent.mkdir(parents=True, exist_ok=True)
-engine = create_async_engine(
- f"sqlite+aiosqlite:///{settings.sqlite_path}",
- echo=False,
-)
+# Seconds a connection waits for SQLite's write lock before giving up with
+# "database is locked". The driver's own default is 5, which a scan, a sync and
+# a status cycle landing in the same moment can outlast on slow storage.
+SQLITE_LOCK_TIMEOUT = 30
+
+
+def create_app_engine(sqlite_path: str | Path) -> AsyncEngine:
+ return create_async_engine(
+ f"sqlite+aiosqlite:///{sqlite_path}",
+ echo=False,
+ connect_args={"timeout": SQLITE_LOCK_TIMEOUT},
+ )
+
+
+engine = create_app_engine(settings.sqlite_path)
AsyncSessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
diff --git a/backend/tests/test_db_engine.py b/backend/tests/test_db_engine.py
new file mode 100644
index 0000000..b877643
--- /dev/null
+++ b/backend/tests/test_db_engine.py
@@ -0,0 +1,20 @@
+"""The application engine's SQLite connection settings."""
+import pytest
+
+from app.db.database import SQLITE_LOCK_TIMEOUT, create_app_engine
+
+pytestmark = pytest.mark.asyncio
+
+
+async def test_engine_waits_for_the_write_lock(tmp_path):
+ """Writers queue on a busy database instead of failing after the driver's
+ default 5 s with "database is locked" (#539)."""
+ engine = create_app_engine(tmp_path / "test.db")
+ try:
+ async with engine.connect() as conn:
+ busy_ms = (await conn.exec_driver_sql("PRAGMA busy_timeout")).scalar()
+ finally:
+ await engine.dispose()
+
+ assert SQLITE_LOCK_TIMEOUT > 5
+ assert busy_ms == SQLITE_LOCK_TIMEOUT * 1000
diff --git a/backend/tests/test_scheduler.py b/backend/tests/test_scheduler.py
index f6ee084..4cc7693 100644
--- a/backend/tests/test_scheduler.py
+++ b/backend/tests/test_scheduler.py
@@ -3,6 +3,7 @@ import uuid
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from sqlalchemy.exc import OperationalError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.core.scheduler import (
@@ -204,6 +205,115 @@ async def test_run_status_checks_handles_check_error_gracefully(mem_db):
assert call_count == 2
+async def test_run_status_checks_saves_the_cycle_in_one_commit(mem_db):
+ """One write transaction per cycle, not one per device (#539).
+
+ SQLite has a single write lock: a commit per device queued as many writers
+ as there are devices, and the last ones timed out with "database is locked".
+ """
+ async with mem_db() as session:
+ devices = [_make_device(check_method="ping", ip=f"10.0.0.{i}") for i in range(1, 4)]
+ session.add_all(devices)
+ await session.commit()
+ device_ids = [d.id for d in devices]
+
+ commits = 0
+ real_commit = AsyncSession.commit
+
+ async def counting_commit(self):
+ nonlocal commits
+ commits += 1
+ await real_commit(self)
+
+ with patch("app.core.scheduler.AsyncSessionLocal", mem_db), \
+ patch("app.core.scheduler.check_node", new_callable=AsyncMock,
+ return_value={"status": "online", "response_time_ms": 5}), \
+ patch("app.api.routes.status.broadcast_status", new_callable=AsyncMock), \
+ patch.object(AsyncSession, "commit", counting_commit):
+ await _run_status_checks()
+
+ assert commits == 1
+ async with mem_db() as session:
+ for device_id in device_ids:
+ updated = await session.get(InventoryDevice, device_id)
+ assert updated is not None
+ assert updated.status_live == "online"
+ assert updated.last_seen is not None
+
+
+async def test_run_status_checks_broadcasts_even_when_the_save_fails(mem_db):
+ """A locked database must not hide a probe that answered (#539)."""
+ async with mem_db() as session:
+ session.add_all([
+ _make_device(check_method="ping", ip="10.0.0.1"),
+ _make_device(check_method="ping", ip="10.0.0.2"),
+ ])
+ await session.commit()
+
+ async def locked_commit(self):
+ raise OperationalError("UPDATE device_inventory", {}, Exception("database is locked"))
+
+ with patch("app.core.scheduler.AsyncSessionLocal", mem_db), \
+ patch("app.core.scheduler.check_node", new_callable=AsyncMock,
+ return_value={"status": "online", "response_time_ms": 5}), \
+ patch("app.api.routes.status.broadcast_status", new_callable=AsyncMock) as mock_broadcast, \
+ patch.object(AsyncSession, "commit", locked_commit):
+ await _run_status_checks() # must not raise
+
+ assert mock_broadcast.await_count == 2
+ assert {c.kwargs["status"] for c in mock_broadcast.await_args_list} == {"online"}
+
+
+async def test_run_status_checks_saves_even_when_the_broadcast_fails(mem_db):
+ """The stored status does not depend on a WebSocket client being reachable."""
+ async with mem_db() as session:
+ device = _make_device(check_method="ping", ip="10.0.0.1")
+ session.add(device)
+ await session.commit()
+ device_id = device.id
+
+ with patch("app.core.scheduler.AsyncSessionLocal", mem_db), \
+ patch("app.core.scheduler.check_node", new_callable=AsyncMock,
+ return_value={"status": "offline", "response_time_ms": None}), \
+ patch("app.api.routes.status.broadcast_status", new_callable=AsyncMock,
+ side_effect=RuntimeError("socket closed")):
+ await _run_status_checks() # must not raise
+
+ async with mem_db() as session:
+ updated = await session.get(InventoryDevice, device_id)
+ assert updated is not None
+ assert updated.status_live == "offline"
+
+
+async def test_run_status_checks_keeps_the_devices_whose_probe_answered(mem_db):
+ """A probe that raises drops only its own device from the cycle's save."""
+ async with mem_db() as session:
+ broken = _make_device(check_method="ping", ip="10.0.0.1")
+ healthy = _make_device(check_method="ping", ip="10.0.0.2")
+ session.add_all([broken, healthy])
+ await session.commit()
+ broken_id, healthy_id = broken.id, healthy.id
+
+ async def flaky_check(method, target, ip):
+ if ip == "10.0.0.1":
+ raise RuntimeError("timeout")
+ return {"status": "online", "response_time_ms": 1}
+
+ with patch("app.core.scheduler.AsyncSessionLocal", mem_db), \
+ patch("app.core.scheduler.check_node", side_effect=flaky_check), \
+ patch("app.api.routes.status.broadcast_status", new_callable=AsyncMock) as mock_broadcast:
+ await _run_status_checks()
+
+ mock_broadcast.assert_awaited_once()
+ async with mem_db() as session:
+ assert (await session.get(InventoryDevice, healthy_id)).status_live == "online"
+ assert (await session.get(InventoryDevice, broken_id)).status_live == "unknown"
+
+
# ---------------------------------------------------------------------------
# start_scheduler / stop_scheduler
# ---------------------------------------------------------------------------