diff --git a/modules/videos/test/test_transcode_job.py b/modules/videos/test/test_transcode_job.py index 7c711cf2..eb775c3c 100644 --- a/modules/videos/test/test_transcode_job.py +++ b/modules/videos/test/test_transcode_job.py @@ -211,3 +211,67 @@ async def test_transcode_video_job_wrol_mode(test_session, test_directory, async assert 'WROL Mode' in record['error'] mock_run.assert_not_called() assert video_path.read_bytes() == before + + +@pytest.mark.asyncio +async def test_transcode_video_job_retargets_before_deleting(test_session, test_directory, async_client, + video_factory): + """When the suffix changes, the FileGroup is pointed at the new file (and committed) while the + old file still exists; the old file is deleted only afterwards. A crash in between then leaves + both files with the database pointing at a real one.""" + from modules.videos import transcode as transcode_module + + video_path = test_directory / 'videos/NO CHANNEL/movie.webm' + video_path.parent.mkdir(parents=True, exist_ok=True) + video = video_factory(with_video_file=video_path) + test_session.commit() + seen = {} + + real_retarget = transcode_module.retarget_file_group + + def spy_retarget(file_group_id, old_path, new_path): + seen['old_exists'] = old_path.exists() + seen['new_exists'] = new_path.exists() + real_retarget(file_group_id, old_path, new_path) + test_session.expire_all() + seen['db_primary'] = Video.find_by_file_group_id(test_session, file_group_id).file_group.primary_path + + async def fake_run_command(cmd, stdout_callback=None, **kwargs): + if cmd[-1] == '-': + return CommandResult(return_code=0, cancelled=False, stdout=b'', stderr=b'', elapsed=0) + shutil.copy(PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4', cmd[-1]) + return CommandResult(return_code=0, cancelled=False, stdout=b'', stderr=b'', elapsed=1) + + with mock.patch('wrolpi.cmd.run_command', side_effect=fake_run_command), \ + mock.patch.object(transcode_module, 'retarget_file_group', side_effect=spy_retarget): + job_id = transcode_video_job.enqueue(file_group_id=video.file_group_id, video_codec='h264', + audio_codec='aac', container='mp4') + record = await jobs.wait_for_job(job_id) + + assert record['status'] == jobs.COMPLETE, record + new_path = test_directory / 'videos/NO CHANNEL/movie.mp4' + assert seen == {'old_exists': True, 'new_exists': True, 'db_primary': new_path}, seen + assert not video_path.exists(), 'The old file is deleted once the database points at the new one' + assert new_path.is_file() + + +@pytest.mark.asyncio +async def test_transcode_video_file_keep_original(test_directory, async_client): + """`transcode_video_file(keep_original=True)` renames the output into place but leaves the + original for the caller to delete once its records point at the new file.""" + from modules.videos.transcode import transcode_video_file + video_path = test_directory / 'video.webm' + video_path.write_bytes(b'fake video data') + + async def fake_run_command(cmd, **kwargs): + if cmd[-1] == '-': + return CommandResult(return_code=0, cancelled=False, stdout=b'', stderr=b'', elapsed=0) + shutil.copy(PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4', cmd[-1]) + return CommandResult(return_code=0, cancelled=False, stdout=b'', stderr=b'', elapsed=1) + + with mock.patch('modules.videos.transcode.run_command', side_effect=fake_run_command): + result = await transcode_video_file(video_path, target_vcodec='h264', target_acodec='aac', + container='mp4', keep_original=True) + + assert result == test_directory / 'video.mp4' and result.is_file() + assert video_path.read_bytes() == b'fake video data', 'The original is kept' diff --git a/modules/videos/transcode.py b/modules/videos/transcode.py index 73a396ab..08f14633 100644 --- a/modules/videos/transcode.py +++ b/modules/videos/transcode.py @@ -124,14 +124,17 @@ async def transcode_video_file(video_path: pathlib.Path, target_vcodec: Optional[str] = None, target_acodec: Optional[str] = None, container: str = 'mp4', - duration: Optional[float] = None) -> pathlib.Path: + duration: Optional[float] = None, + keep_original: bool = False) -> pathlib.Path: """Transcode a video file in place (same stem, possibly a new container extension). Only one transcode runs at a time machine-wide (across all Sanic workers); this call waits for its turn. Only the stream(s) with a target are re-encoded; the other stream is copied. The output is written to a temporary file in the same directory, then atomically renamed over - the final path. The original file is deleted if the extension changed. Returns the final - path. + the final path. The original file is deleted if the extension changed, unless + `keep_original`: a caller with database records pointing at the original must retarget them + first, then delete it (see `transcode_video_job`), so a crash never leaves the records pointing + at a deleted file. Returns the final path. When run inside a Job (see `wrolpi.jobs`), ffmpeg's output is captured into the Job log and, if `duration` (seconds) is known, progress is reported to the Job. @@ -148,7 +151,8 @@ async def transcode_video_file(video_path: pathlib.Path, lock = await _acquire_transcode_lock() try: - return await _transcode_video_file(video_path, target_vcodec, target_acodec, container, duration) + return await _transcode_video_file(video_path, target_vcodec, target_acodec, container, duration, + keep_original) finally: lock.release() @@ -249,7 +253,7 @@ def make_ffmpeg_progress_parser(duration: Optional[float], set_progress: Callabl async def _transcode_video_file(video_path: pathlib.Path, target_vcodec: Optional[str], target_acodec: Optional[str], container: str, - duration: Optional[float] = None) -> pathlib.Path: + duration: Optional[float] = None, keep_original: bool = False) -> pathlib.Path: """The ffmpeg work of `transcode_video_file`; the caller holds the transcode lock.""" # Notify here, after the lock: the wait for another transcode can last hours, and the user # should hear "Transcoding" only when this file's work actually begins. @@ -320,7 +324,7 @@ async def _transcode_video_file(video_path: pathlib.Path, target_vcodec: Optiona # The old ffprobe sidecar describes the old streams. video_path.with_suffix('.ffprobe.json').unlink(missing_ok=True) tmp_path.rename(final_path) - if final_path != video_path: + if final_path != video_path and not keep_original: video_path.unlink() final_path.chmod(DEFAULT_FILE_PERMISSIONS) @@ -345,6 +349,27 @@ def validate_transcode_request(video_codec: Optional[str], audio_codec: Optional raise ValueError(f'Unsupported container {container!r}; supported: {TRANSCODE_CONTAINERS}') +def retarget_file_group(file_group_id: int, old_path: pathlib.Path, new_path: pathlib.Path): + """Point a Video's FileGroup at the transcoded file and mark it for re-modeling. Committed.""" + from modules.videos.models import Video + from wrolpi.files.lib import get_mimetype + + with get_db_session(commit=True) as session: + video = Video.find_by_file_group_id(session, file_group_id) + file_group = video.file_group + if new_path != old_path: + mimetype = get_mimetype(new_path) + file_group.files = [ + {**i, 'path': new_path.name, 'mimetype': mimetype} if i['path'] == old_path.name else i + for i in file_group.files + ] + file_group.primary_path = new_path + file_group.mimetype = mimetype + # The streams changed: the modeler must ffprobe the file again. + video.ffprobe_json = None + file_group.indexed = False + + @register_job('transcode_video') async def transcode_video_job(file_group_id: int, video_codec: Optional[str] = None, audio_codec: Optional[str] = None, container: str = 'mp4') -> dict: @@ -352,7 +377,6 @@ async def transcode_video_job(file_group_id: int, video_codec: Optional[str] = N Run as a Job (`transcode_video_job.enqueue(...)`) so the user can watch and cancel it.""" from modules.videos.models import Video - from wrolpi.files.lib import get_mimetype from wrolpi.files.worker import file_worker # The API refuses to queue in WROL Mode; this catches a Job queued before it was enabled. @@ -368,24 +392,17 @@ async def transcode_video_job(file_group_id: int, video_codec: Optional[str] = N if not video_path or not video_path.is_file(): raise RuntimeError(f'Video file does not exist: {video_path}') - final_path = await transcode_video_file(video_path, video_codec, audio_codec, container, duration=duration) + # The original is kept until the database points at the new file (below). + final_path = await transcode_video_file(video_path, video_codec, audio_codec, container, duration=duration, + keep_original=True) - # Point the existing FileGroup at the new file *before* refreshing. A refresh which finds a - # new filename on disk would delete this FileGroup and create another, losing tags and history. - with get_db_session(commit=True) as session: - video = Video.find_by_file_group_id(session, file_group_id) - file_group = video.file_group - if final_path != video_path: - file_group.files = [ - {**i, 'path': final_path.name, 'mimetype': get_mimetype(final_path)} - if i['path'] == video_path.name else i - for i in file_group.files - ] - file_group.primary_path = final_path - file_group.mimetype = get_mimetype(final_path) - # The streams changed: the modeler must ffprobe the file again. - video.ffprobe_json = None - file_group.indexed = False + # Point the existing FileGroup at the new file *before* deleting the original and *before* + # refreshing. A crash after the delete would leave the database pointing at a missing file; + # a refresh which finds a new filename on disk would delete this FileGroup and create another, + # losing tags and history. + retarget_file_group(file_group_id, video_path, final_path) + if final_path != video_path: + video_path.unlink(missing_ok=True) job_id = file_worker.queue_refresh([final_path], send_events=False) await file_worker.wait_for_job(job_id) diff --git a/wrolpi/jobs.py b/wrolpi/jobs.py index 04cf2d9a..04d4d9a5 100644 --- a/wrolpi/jobs.py +++ b/wrolpi/jobs.py @@ -62,6 +62,9 @@ FINISHED_STATUSES = (COMPLETE, FAILED, CANCELLED) JOB_LOG_LINES = 200 # Finished Jobs kept for the UI/API before the oldest are forgotten. JOB_HISTORY_LIMIT = 100 +# Pending Jobs allowed at once; `enqueue_job` refuses past this so a runaway client cannot grow +# shared memory without bound. +JOB_PENDING_LIMIT = 100 # How often the running Job checks whether it has been cancelled from another process. JOB_CANCEL_POLL_SECONDS = 0.05 if PYTEST else 1 # The Job log lives in this process; it is copied to the shared dict at most this often. @@ -131,6 +134,9 @@ def enqueue_job(name: str, description: str = None, **kwargs) -> str: cancel_requested=False, ) with _lock(): + pending = sum(1 for i in _jobs().values() if i['status'] == PENDING) + if pending >= JOB_PENDING_LIMIT: + raise InvalidJob(f'Too many pending jobs ({pending}); try again once some have finished') _jobs()[job_id] = record _prune_finished_jobs() _queue().put_nowait(job_id) @@ -192,6 +198,22 @@ def cancel_job(job_id: str) -> dict: return record +def _claim_job(job_id: str) -> Optional[dict]: + """Move a Job from PENDING to RUNNING in one step under the lock; returns the running record, + or None when the Job is no longer pending (cancelled while queued, or already claimed). + + Reading the status and writing RUNNING separately let a cancel land in between and be + overwritten, running a Job the user had cancelled.""" + with _lock(): + record = _jobs().get(job_id) + if not record or record['status'] != PENDING: + return None + record = dict(record) + record.update(status=RUNNING, started_at=now().isoformat(), pid=os.getpid()) + _jobs()[job_id] = record + return record + + def _cancel_requested(job_id: str) -> bool: record = _jobs().get(job_id) return bool(record and record.get('cancel_requested')) @@ -240,12 +262,18 @@ class JobContext: if stdout_callback: stdout_callback(line) + # Its own session: killing the command kills anything it spawned, as elsewhere in WROLPi. + kwargs.setdefault('start_new_session', True) result = await run_command(cmd, stdout_callback=_callback, **kwargs) if result.stderr: for line in result.stderr.decode(errors='replace').splitlines()[-JOB_LOG_LINES:]: if line.strip(): self.log(line) self.flush() + if result.cancelled: + # `run_command` swallows the cancellation and returns; a handler checking return codes + # must not mistake a killed command for a normal exit. + raise asyncio.CancelledError(f'Command was cancelled: {cmd[0]}') return result @@ -289,8 +317,8 @@ def _json_safe(value): async def _run_job(job_id: str): """Run one Job to completion (or failure/cancellation) in this process.""" - record = _jobs().get(job_id) - if not record or record['status'] != PENDING: + record = _claim_job(job_id) + if not record: # Cancelled while it was waiting in the queue. return @@ -302,7 +330,6 @@ async def _run_job(job_id: str): finished_at=now().isoformat()) return - _update_job(job_id, status=RUNNING, started_at=now().isoformat(), pid=os.getpid()) token = _current_job.set(context) try: async def call(): diff --git a/wrolpi/test/test_jobs.py b/wrolpi/test/test_jobs.py index c9f7b026..a2e1a628 100644 --- a/wrolpi/test/test_jobs.py +++ b/wrolpi/test/test_jobs.py @@ -1,5 +1,6 @@ import asyncio import logging +from unittest import mock from http import HTTPStatus import pytest @@ -210,3 +211,56 @@ async def test_jobs_api(async_client): request, response = await async_client.get('/api/jobs/nope') assert response.status == HTTPStatus.NOT_FOUND + + +@pytest.mark.asyncio +async def test_jobs_claim_is_atomic(async_client): + """The worker claims a Job (PENDING -> RUNNING) in one step under the lock, so a cancel that + lands first wins and the Job never runs; a cancel that lands after only requests a stop.""" + from wrolpi.jobs import _claim_job + + cancelled_first = enqueue_job('test_sync', value='a') + cancel_job(cancelled_first) + assert _claim_job(cancelled_first) is None, 'A cancelled Job cannot be claimed' + assert get_job(cancelled_first)['status'] == jobs.CANCELLED, 'The claim must not promote it to RUNNING' + + claimed = enqueue_job('test_sync', value='b') + record = _claim_job(claimed) + assert record['status'] == jobs.RUNNING and record['pid'] and record['started_at'] + assert get_job(claimed)['status'] == jobs.RUNNING + assert _claim_job(claimed) is None, 'A Job is claimed once' + # Cancelling a claimed Job only asks it to stop. + assert cancel_job(claimed)['status'] == jobs.RUNNING + assert get_job(claimed)['cancel_requested'] is True + + +@pytest.mark.asyncio +async def test_jobs_pending_limit(async_client): + """The queue refuses new Jobs past a pending cap, so a runaway client cannot grow shared memory.""" + with mock.patch.object(jobs, 'JOB_PENDING_LIMIT', 2): + first = enqueue_job('test_slow', seconds=30) + second = enqueue_job('test_slow', seconds=30) + with pytest.raises(InvalidJob, match='pending'): + enqueue_job('test_slow', seconds=30) + # A cancelled Job no longer counts. + cancel_job(first) + third = enqueue_job('test_slow', seconds=30) + for job_id in (second, third): + cancel_job(job_id) + assert await process_job_queue() == 3, 'Cancelled ids are drained as no-ops' + assert [i['status'] for i in get_jobs()] == [jobs.CANCELLED] * 3 + + +@pytest.mark.asyncio +async def test_jobs_run_command_cancel_semantics(async_client): + """A Job's subprocess runs in its own session (the whole group dies with it), and a killed + command raises rather than returning a result a handler could mistake for a normal exit.""" + from wrolpi.cmd import CommandResult + from wrolpi.jobs import JobContext + + context = JobContext('test-1', 'test') + killed = CommandResult(return_code=-9, cancelled=True, stdout=b'', stderr=b'', elapsed=1) + with mock.patch('wrolpi.cmd.run_command', return_value=killed) as mock_run: + with pytest.raises(asyncio.CancelledError): + await context.run_command(('sleep', '30')) + assert mock_run.call_args.kwargs['start_new_session'] is True