diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index d062ee384..3f3839afe 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -7,8 +7,9 @@ from itertools import batched, chain from typing import Any, Final import socketio # type: ignore +from redis import Redis from rq import Worker, get_current_job -from rq.exceptions import NoSuchJobError +from rq.exceptions import AbandonedJobError, NoSuchJobError from rq.job import Job, JobStatus from rq.registry import ScheduledJobRegistry from sqlalchemy.exc import IntegrityError @@ -56,6 +57,7 @@ from handler.redis_handler import ( high_prio_queue, low_prio_queue, redis_client, + scan_queue, ) from handler.scan_handler import ( MetadataSource, @@ -133,12 +135,14 @@ def _get_running_scan_job() -> Job | None: def _get_queued_scan_jobs() -> list[Job]: """Scans sitting on a worker queue, waiting to be picked up. - Socket scans go to the high priority queue and watcher scans to the low - priority one, once their delay is up. + The other queues are still read because a scan enqueued before scans had + their own queue is on one of them, and it will still run. """ jobs: dict[str, Job] = {} - for job in chain(high_prio_queue.get_jobs(), low_prio_queue.get_jobs()): + for job in chain( + scan_queue.get_jobs(), high_prio_queue.get_jobs(), low_prio_queue.get_jobs() + ): if ( isinstance(job, Job) and _is_scan_job(job) @@ -150,8 +154,8 @@ def _get_queued_scan_jobs() -> list[Job]: def _scheduled_scan_registry() -> ScheduledJobRegistry: - """Where delayed scans wait, which is only ever the watcher's queue.""" - return ScheduledJobRegistry(queue=low_prio_queue) + """Where delayed scans wait until a worker releases them.""" + return ScheduledJobRegistry(queue=scan_queue) def _get_scheduled_scan_jobs() -> list[Job]: @@ -204,6 +208,29 @@ def drop_stale_scheduled_scans() -> int: return dropped +def report_scan_failure( + job: Job, connection: Redis, exc_type: type, exc_value: BaseException, tb: Any +) -> None: + """Tell the clients a scan is over when the scan could not say so itself. + + A worker killed mid-scan never reaches the handler that emits this, so the + clients would keep showing a scan that no longer exists. RQ runs this from + whichever worker reaps the job, which is why the scan queue having a worker + of its own matters: another one is left to notice. + """ + # Every other failure is reported by the scan as it unwinds, and emitting + # here too would report it twice. + if exc_type is not AbandonedJobError: + return + + log.warning(f"{emoji.EMOJI_STOP_SIGN} Scan {job.id} was abandoned by its worker") + asyncio.run( + _get_socket_manager().emit( + "scan:done_ko", "the worker running it stopped unexpectedly" + ) + ) + + def _scan_job_label(job: Job) -> str: """How to refer to a scan job when reporting it to a client.""" return str(job.meta.get("task_name") or "A scan") @@ -1362,8 +1389,9 @@ async def scan_handler(sid: str, options: dict[str, Any]): platform_fs_slugs=platform_fs_slugs, ) - return high_prio_queue.enqueue( + return scan_queue.enqueue( scan_platforms, + on_failure=report_scan_failure, platform_ids=platform_ids, metadata_sources=metadata_sources, scan_type=scan_type, diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index e27a4ec9f..cdcc285d0 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -32,6 +32,7 @@ from handler.redis_handler import ( high_prio_queue, low_prio_queue, redis_client, + scan_queue, ) from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS from tasks.tasks import Task, TaskType, run_task_by_name @@ -43,6 +44,9 @@ router = APIRouter( ) +# Every queue a job can be on, so the task list does not miss one. +ALL_QUEUES: Final = (scan_queue, high_prio_queue, default_queue, low_prio_queue) + # Scheduled tasks an admin can see and trigger. The rest of the catalog runs on # its schedule without being surfaced. VISIBLE_SCHEDULED_TASKS: Final = ( @@ -208,25 +212,12 @@ async def get_tasks_status(request: Request) -> list[TaskStatusResponse]: all_tasks.append(_build_task_status_response(current_job)) # Get all jobs from the queues (including completed ones) - low_prio_jobs = low_prio_queue.get_jobs() - default_prio_jobs = default_queue.get_jobs() - high_prio_jobs = high_prio_queue.get_jobs() + for queue in ALL_QUEUES: + for job in queue.get_jobs(): + all_tasks.append(_build_task_status_response(job)) - for job in low_prio_jobs + default_prio_jobs + high_prio_jobs: - all_tasks.append(_build_task_status_response(job)) - - # Get finished jobs from all queues - finished_registries = [ - FinishedJobRegistry(queue=low_prio_queue), - FinishedJobRegistry(queue=default_queue), - FinishedJobRegistry(queue=high_prio_queue), - ] - - failed_registries = [ - FailedJobRegistry(queue=low_prio_queue), - FailedJobRegistry(queue=default_queue), - FailedJobRegistry(queue=high_prio_queue), - ] + finished_registries = [FinishedJobRegistry(queue=queue) for queue in ALL_QUEUES] + failed_registries = [FailedJobRegistry(queue=queue) for queue in ALL_QUEUES] # Process finished jobs for registry in finished_registries: diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index fa2761bed..135732c1a 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -1,7 +1,7 @@ import os import sys from enum import Enum -from typing import Any +from typing import Any, Final from redis import Redis from redis.asyncio import Redis as AsyncRedis @@ -19,11 +19,18 @@ class QueuePrio(Enum): LOW = "low" +# Scans have their own queue, and their own worker consumes it. A library scan +# runs for hours, so sharing a worker with the rest would hold up every cleanup +# and metadata refresh behind it, and a single scan worker keeps two scans from +# ever running at once. +SCAN_QUEUE_NAME: Final = "scans" + redis_client = Redis.from_url(REDIS_URL) high_prio_queue = Queue(name=QueuePrio.HIGH.value, connection=redis_client) default_queue = Queue(name=QueuePrio.DEFAULT.value, connection=redis_client) low_prio_queue = Queue(name=QueuePrio.LOW.value, connection=redis_client) +scan_queue = Queue(name=SCAN_QUEUE_NAME, connection=redis_client) def __get_sync_cache() -> Redis: diff --git a/backend/tasks/cron_config.py b/backend/tasks/cron_config.py index ea9f47236..3ec7fdf0e 100644 --- a/backend/tasks/cron_config.py +++ b/backend/tasks/cron_config.py @@ -7,7 +7,8 @@ simply leaves it out. from rq import cron -from handler.redis_handler import QueuePrio +from endpoints.responses import TaskType +from handler.redis_handler import SCAN_QUEUE_NAME, QueuePrio from logger.logger import log from tasks.registry import SCHEDULED_TASKS from tasks.tasks import run_task_by_name @@ -16,9 +17,15 @@ for name, task in SCHEDULED_TASKS.items(): if not task.enabled or not task.cron_string: continue + # The scheduled rescan belongs on the queue the scan worker consumes, so it + # neither holds up the other tasks nor overlaps another scan. + queue_name = ( + SCAN_QUEUE_NAME if task.task_type is TaskType.SCAN else QueuePrio.LOW.value + ) + cron.register( run_task_by_name, - QueuePrio.LOW.value, + queue_name, kwargs={"name": name}, cron=task.cron_string, job_timeout=task.timeout, diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index 4ff1164bb..f3043be95 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -5,7 +5,11 @@ from unittest.mock import AsyncMock, MagicMock, Mock import pytest import socketio -from rq.exceptions import InvalidJobOperation, NoSuchJobError +from rq.exceptions import ( + AbandonedJobError, + InvalidJobOperation, + NoSuchJobError, +) from rq.job import Job, JobStatus from endpoints.sockets import scan as scan_module @@ -703,7 +707,7 @@ class TestScanAuthorization: mocker.patch.object( scan_module, "get_authenticated_user", AsyncMock(return_value=None) ) - enqueue = mocker.patch.object(scan_module.high_prio_queue, "enqueue") + enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue") scan_platforms_mock = mocker.patch.object( scan_module, "scan_platforms", AsyncMock() ) @@ -1714,7 +1718,7 @@ def patch_scan_jobs( mocker, *, running=None, - high_queued=(), + scan_queued=(), low_queued=(), scheduled=(), worker_lost=False, @@ -1730,8 +1734,9 @@ def patch_scan_jobs( worker.get_current_job.return_value = running mocker.patch.object(scan_module.Worker, "all", return_value=[worker]) mocker.patch.object( - scan_module.high_prio_queue, "get_jobs", return_value=list(high_queued) + scan_module.scan_queue, "get_jobs", return_value=list(scan_queued) ) + mocker.patch.object(scan_module.high_prio_queue, "get_jobs", return_value=[]) mocker.patch.object( scan_module.low_prio_queue, "get_jobs", return_value=list(low_queued) ) @@ -1762,9 +1767,11 @@ class TestScanConcurrency: ) mocker.patch.object(scan_module, "DEV_MODE", False) - async def test_enqueues_when_nothing_running(self, mocker, emit): + async def test_enqueues_on_the_scan_queue_when_nothing_running(self, mocker, emit): + # The scan queue has a worker of its own, so a scan cannot sit behind a + # cleanup, nor hold one up for hours. patch_scan_jobs(mocker) - enqueue = mocker.patch.object(scan_module.high_prio_queue, "enqueue") + enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) @@ -1772,7 +1779,7 @@ class TestScanConcurrency: async def test_refuses_when_a_scan_is_running(self, mocker, emit): patch_scan_jobs(mocker, running=make_job(SCAN_PLATFORMS_FUNC)) - enqueue = mocker.patch.object(scan_module.high_prio_queue, "enqueue") + enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) @@ -1781,8 +1788,8 @@ class TestScanConcurrency: assert emit.await_args.args[0] == "scan:done_ko" async def test_refuses_when_a_scan_is_queued(self, mocker, emit): - patch_scan_jobs(mocker, high_queued=[make_job(SCAN_PLATFORMS_FUNC)]) - enqueue = mocker.patch.object(scan_module.high_prio_queue, "enqueue") + patch_scan_jobs(mocker, scan_queued=[make_job(SCAN_PLATFORMS_FUNC)]) + enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) @@ -1791,7 +1798,7 @@ class TestScanConcurrency: async def test_refuses_when_a_watcher_scan_is_queued(self, mocker, emit): # Watcher scans land in the low priority queue, not the high one. patch_scan_jobs(mocker, low_queued=[make_job(SCAN_PLATFORMS_FUNC)]) - enqueue = mocker.patch.object(scan_module.high_prio_queue, "enqueue") + enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) @@ -1804,18 +1811,33 @@ class TestScanConcurrency: mocker, scheduled=[make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.SCHEDULED)], ) - enqueue = mocker.patch.object(scan_module.high_prio_queue, "enqueue") + enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) enqueue.assert_called_once() + async def test_a_scan_left_on_an_older_queue_still_blocks(self, mocker, emit): + # A scan enqueued before scans had their own queue is on the high or low + # queue, and a worker will still run it. + patch_scan_jobs(mocker) + mocker.patch.object( + scan_module.high_prio_queue, + "get_jobs", + return_value=[make_job(SCAN_PLATFORMS_FUNC)], + ) + enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue") + + await scan_handler("sid", {"type": "quick"}) + + enqueue.assert_not_called() + async def test_a_cancelled_queued_scan_does_not_block(self, mocker, emit): patch_scan_jobs( mocker, - high_queued=[make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.CANCELED)], + scan_queued=[make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.CANCELED)], ) - enqueue = mocker.patch.object(scan_module.high_prio_queue, "enqueue") + enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) @@ -1827,8 +1849,8 @@ class TestScanConcurrency: # RQ raises rather than reporting a status once the job hash expires. job = make_job(SCAN_PLATFORMS_FUNC) job.get_status.side_effect = InvalidJobOperation - patch_scan_jobs(mocker, high_queued=[job]) - enqueue = mocker.patch.object(scan_module.high_prio_queue, "enqueue") + patch_scan_jobs(mocker, scan_queued=[job]) + enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) @@ -1838,7 +1860,7 @@ class TestScanConcurrency: self, mocker, emit ): patch_scan_jobs(mocker, worker_lost=True) - enqueue = mocker.patch.object(scan_module.high_prio_queue, "enqueue") + enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) @@ -1851,7 +1873,7 @@ class TestScanConcurrency: SCAN_PLATFORMS_FUNC, status=JobStatus.STARTED, task_name="Quick Scan" ), ) - mocker.patch.object(scan_module.high_prio_queue, "enqueue") + mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) @@ -1866,7 +1888,7 @@ class TestScanConcurrency: SCAN_PLATFORMS_FUNC, status=JobStatus.CANCELED, task_name="Quick Scan" ), ) - mocker.patch.object(scan_module.high_prio_queue, "enqueue") + mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) @@ -1874,9 +1896,9 @@ class TestScanConcurrency: async def test_refusal_reports_a_queued_scan_as_queued(self, mocker, emit): patch_scan_jobs( - mocker, high_queued=[make_job(SCAN_PLATFORMS_FUNC, task_name="Full Scan")] + mocker, scan_queued=[make_job(SCAN_PLATFORMS_FUNC, task_name="Full Scan")] ) - mocker.patch.object(scan_module.high_prio_queue, "enqueue") + mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) @@ -1886,7 +1908,7 @@ class TestScanConcurrency: # Every task runs through the same runner, so the scheduled rescan is # only recognisable by the type its job carries. patch_scan_jobs(mocker, running=make_task_job()) - enqueue = mocker.patch.object(scan_module.high_prio_queue, "enqueue") + enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) @@ -1897,11 +1919,11 @@ class TestScanConcurrency: patch_scan_jobs( mocker, running=make_job(CLEANUP_FUNC), - high_queued=[make_job(CLEANUP_FUNC)], + scan_queued=[make_job(CLEANUP_FUNC)], low_queued=[make_job(CLEANUP_FUNC)], scheduled=[make_job(CLEANUP_FUNC, status=JobStatus.SCHEDULED)], ) - enqueue = mocker.patch.object(scan_module.high_prio_queue, "enqueue") + enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue") await scan_handler("sid", {"type": "quick"}) @@ -2005,7 +2027,7 @@ class TestStopScan: async def test_cancels_queued_scans(self, mocker, emit, redis): queued = [make_job(SCAN_PLATFORMS_FUNC), make_job(SCAN_PLATFORMS_FUNC)] patch_scan_jobs( - mocker, running=make_job(SCAN_PLATFORMS_FUNC), high_queued=queued + mocker, running=make_job(SCAN_PLATFORMS_FUNC), scan_queued=queued ) await stop_scan_handler("sid") @@ -2031,7 +2053,7 @@ class TestStopScan: # Stopping a scan that has not been picked up yet must still drop it, # and must not leave a stop flag behind for the next scan to trip on. queued = [make_job(SCAN_PLATFORMS_FUNC)] - patch_scan_jobs(mocker, high_queued=queued) + patch_scan_jobs(mocker, scan_queued=queued) await stop_scan_handler("sid") @@ -2084,3 +2106,37 @@ class TestDropStaleScheduledScans: assert scan_module.drop_stale_scheduled_scans() == 0 job.cancel.assert_not_called() + + +class TestReportScanFailure: + """A scan whose worker died cannot report itself, so RQ reports for it.""" + + @pytest.fixture + def emit(self, mocker): + manager = AsyncMock() + mocker.patch.object(scan_module, "_get_socket_manager", return_value=manager) + return manager.emit + + def test_reports_a_scan_its_worker_abandoned(self, emit): + scan_module.report_scan_failure( + make_job(SCAN_PLATFORMS_FUNC), + MagicMock(), + AbandonedJobError, + AbandonedJobError(), + None, + ) + + emit.assert_awaited_once() + assert emit.await_args.args[0] == "scan:done_ko" + + def test_stays_quiet_for_a_failure_the_scan_already_reported(self, emit): + # scan_platforms emits on its way out, so reporting here would double up. + scan_module.report_scan_failure( + make_job(SCAN_PLATFORMS_FUNC), + MagicMock(), + RuntimeError, + RuntimeError("boom"), + None, + ) + + emit.assert_not_awaited() diff --git a/backend/tests/tasks/test_cron_config.py b/backend/tests/tasks/test_cron_config.py index 54df7d361..87d3afb5c 100644 --- a/backend/tests/tasks/test_cron_config.py +++ b/backend/tests/tasks/test_cron_config.py @@ -2,6 +2,8 @@ import importlib import pytest +from endpoints.responses import TaskType +from handler.redis_handler import SCAN_QUEUE_NAME, QueuePrio from tasks import cron_config from tasks.registry import SCHEDULED_TASKS from tasks.tasks import run_task_by_name @@ -27,7 +29,7 @@ def _task(mocker, *, enabled=True, cron_string="0 4 * * *"): timeout=100, title="Test Task", description="test task", - task_type=mocker.MagicMock(value="cleanup"), + task_type=TaskType.CLEANUP, ) @@ -43,6 +45,18 @@ class TestCronConfig: assert kwargs["kwargs"] == {"name": "test_task"} assert kwargs["cron"] == "0 4 * * *" + def test_a_scan_is_registered_on_the_scan_queue(self, mocker, registered): + task = _task(mocker) + task.task_type = TaskType.SCAN + register = registered({"scan_library": task}) + + assert register.call_args.args[1] == SCAN_QUEUE_NAME + + def test_everything_else_stays_on_the_low_queue(self, mocker, registered): + register = registered({"cleanup": _task(mocker)}) + + assert register.call_args.args[1] == QueuePrio.LOW.value + def test_skips_a_disabled_task(self, mocker, registered): assert registered({"off": _task(mocker, enabled=False)}).call_count == 0 diff --git a/backend/tests/test_watcher.py b/backend/tests/test_watcher.py index e4e7dc049..cfd5c7a32 100644 --- a/backend/tests/test_watcher.py +++ b/backend/tests/test_watcher.py @@ -145,7 +145,7 @@ class TestProcessChanges: @pytest.fixture def enqueue_in(self, mocker): - return mocker.patch.object(watcher_module.low_prio_queue, "enqueue_in") + return mocker.patch.object(watcher_module.scan_queue, "enqueue_in") def rom_change(self, fs_slug: str = "gba"): return (EventType.ADDED, f"{LIBRARY_BASE_PATH}/roms/{fs_slug}/game.gba") diff --git a/backend/watcher.py b/backend/watcher.py index fa442f232..0e04f874d 100644 --- a/backend/watcher.py +++ b/backend/watcher.py @@ -21,6 +21,7 @@ from config import ( from config.config_manager import config_manager as cm from endpoints.sockets.scan import ( get_pending_scan_jobs, + report_scan_failure, scan_platforms, ) from handler.database import db_platform_handler @@ -42,7 +43,7 @@ from handler.metadata import ( meta_steam_handler, meta_tgdb_handler, ) -from handler.redis_handler import get_job_kwargs, low_prio_queue +from handler.redis_handler import get_job_kwargs, scan_queue from handler.scan_handler import MetadataSource, ScanType from logger.formatter import CYAN from logger.formatter import highlight as hl @@ -216,12 +217,13 @@ def process_changes(changes: Sequence[Change]) -> None: # Any change to a platform directory should trigger a full rescan if changes_platform_directory: log.info(f"Platform directory changed, {rescan_in_msg}") - low_prio_queue.enqueue_in( + scan_queue.enqueue_in( time_delta, scan_platforms, platform_ids=[], metadata_sources=metadata_sources, scan_type=ScanType.UPDATE, + on_failure=report_scan_failure, job_timeout=SCAN_TIMEOUT, result_ttl=TASK_RESULT_TTL, meta={ @@ -246,12 +248,13 @@ def process_changes(changes: Sequence[Change]) -> None: continue log.info(f"Change detected in {hl(fs_slug)} folder, {rescan_in_msg}") - low_prio_queue.enqueue_in( + scan_queue.enqueue_in( time_delta, scan_platforms, platform_ids=[db_platform.id], metadata_sources=metadata_sources, scan_type=ScanType.QUICK, + on_failure=report_scan_failure, job_timeout=SCAN_TIMEOUT, result_ttl=TASK_RESULT_TTL, meta={ diff --git a/docker/init_scripts/init b/docker/init_scripts/init index af22f0c07..1bbcdacb9 100755 --- a/docker/init_scripts/init +++ b/docker/init_scripts/init @@ -267,26 +267,40 @@ start_bin_rq_cron() { # Commands to start RQ worker start_bin_rq_worker() { info_log "Starting RQ worker" + start_rq_worker rq_worker high default low +} + +# A scan runs for hours, so it gets its own worker: the queues above keep being +# served while it runs, and one worker on one queue keeps two scans from +# overlapping. +start_bin_rq_scan_worker() { + info_log "Starting RQ scan worker" + start_rq_worker rq_scan_worker scans +} + +# Set PYTHONPATH so RQ can find the tasks module. +# Use a worker class that drops the noisy per-sweep "cleaning registries for +# queue" log line. The maintenance interval keeps its default (~10 min) so +# orphaned STARTED jobs and stale workers are still pruned promptly. +# --with-scheduler releases delayed jobs, which is how the watcher's rescans +# wait out their delay. +start_rq_worker() { + local name="$1" + shift local redis_url redis_url="$(build_redis_url)" - # Set PYTHONPATH so RQ can find the tasks module. - # Use a worker class that drops the noisy per-sweep "cleaning registries for - # queue" log line. The maintenance interval keeps its default (~10 min) so - # orphaned STARTED jobs and stale workers are still pruned promptly. - # --with-scheduler releases delayed jobs, which is how the watcher's rescans - # wait out their delay. PYTHONPATH="/backend:${PYTHONPATH-}" \ RQ_REDIS_URL="${redis_url}" \ rq worker \ --path /backend \ --worker-class handler.rq_worker.RomMWorker \ - --pid /tmp/rq_worker.pid \ + --pid "/tmp/${name}.pid" \ --results-ttl "${TASK_RESULT_TTL:-86400}" \ --logging_level "${LOGLEVEL}" \ --with-scheduler \ - high default low & + "$@" & } start_bin_watcher() { @@ -346,6 +360,7 @@ stop_process_pid() { shutdown() { # shutdown in reverse order stop_process_pid rq_worker + stop_process_pid rq_scan_worker stop_process_pid rq_cron stop_process_pid sync_watcher stop_process_pid watcher @@ -406,6 +421,9 @@ while ! ((exited)); do watchdog_process_pid rq_worker + # Scans get a worker of their own + watchdog_process_pid rq_scan_worker + # only start the watcher if enabled if [[ ${ENABLE_RESCAN_ON_FILESYSTEM_CHANGE} == "true" ]]; then watchdog_process_pid watcher diff --git a/entrypoint.sh b/entrypoint.sh index 7bfd17d41..d00a89188 100644 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -80,15 +80,28 @@ echo "Starting RQ worker..." # orphaned STARTED jobs and stale workers are still pruned promptly. # --with-scheduler releases delayed jobs, which is how the watcher's rescans # wait out their delay. -PYTHONPATH="/app/backend:${PYTHONPATH-}" \ - RQ_REDIS_URL="${REDIS_URL}" \ - rq worker \ - --path /app/backend \ - --worker-class handler.rq_worker.RomMWorker \ - --pid /tmp/rq_worker.pid \ - --logging_level "${LOGLEVEL:-INFO}" \ - --with-scheduler \ - high default low & +start_rq_worker() { + local name="$1" + shift + + PYTHONPATH="/app/backend:${PYTHONPATH-}" \ + RQ_REDIS_URL="${REDIS_URL}" \ + rq worker \ + --path /app/backend \ + --worker-class handler.rq_worker.RomMWorker \ + --pid "/tmp/${name}.pid" \ + --logging_level "${LOGLEVEL:-INFO}" \ + --with-scheduler \ + "$@" & +} + +start_rq_worker rq_worker high default low + +# A scan runs for hours, so it gets its own worker: the queues above keep being +# served while it runs, and one worker on one queue keeps two scans from +# overlapping. +echo "Starting RQ scan worker..." +start_rq_worker rq_scan_worker scans echo "Starting watcher..." watchfiles \