diff --git a/.cspell/dictionary.txt b/.cspell/dictionary.txt index 0f0fd0b0..40739d4d 100644 --- a/.cspell/dictionary.txt +++ b/.cspell/dictionary.txt @@ -180,3 +180,6 @@ zenodo # Language names (POT header examples) Deutsch +getpid +killpg +pids diff --git a/packages/dsw-document-worker/CHANGELOG.md b/packages/dsw-document-worker/CHANGELOG.md index a7d9f028..bf2a752f 100644 --- a/packages/dsw-document-worker/CHANGELOG.md +++ b/packages/dsw-document-worker/CHANGELOG.md @@ -38,6 +38,7 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - Documents no longer fail when a report metric has no measure (`measure` is `null` when nothing answered contributes to the metric); `ReportMetric.measure` is `None` then - The `policy.urlize.extra_schemes` step option is applied to the `urlize.extra_schemes` Jinja policy instead of overwriting `truncate.leeway` +- A Pandoc conversion that exceeds `externals.pandoc.timeout` (`PANDOC_TIMEOUT`) is stopped together with the filters it started, and the document fails with "Exceeded the time limit of N seconds"; before, the worker waited for Pandoc to finish and the timeout had no effect. The error message keeps only the last 64 KiB of Pandoc's stderr ### Removed diff --git a/packages/dsw-templating/dsw/templating/conversions.py b/packages/dsw-templating/dsw/templating/conversions.py index 9ce5f4c6..f609b1e3 100644 --- a/packages/dsw-templating/dsw/templating/conversions.py +++ b/packages/dsw-templating/dsw/templating/conversions.py @@ -1,8 +1,13 @@ from __future__ import annotations +import contextlib import logging +import os import shlex +import signal import subprocess +import sys +import tempfile import typing from . import consts @@ -17,29 +22,67 @@ LOG = logging.getLogger(__name__) +#: how much of the end of stderr goes into the error message +STDERR_LIMIT = 64 * 1024 + + def run_conversion(*, args: list, workdir: str, input_data: bytes, name: str, source_format: FileFormat, target_format: FileFormat, timeout=None) -> bytes: command = ' '.join(args) LOG.info('Calling "%s" to convert from %s to %s', command, source_format, target_format) - try: - proc = subprocess.Popen(args, cwd=workdir, stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=subprocess.PIPE) - except FileNotFoundError as e: - raise FormatConversionError( - name, source_format, target_format, - f'Executable "{args[0]}" not found, is it installed?', - ) from e - with proc: - stdout, stderr = proc.communicate(input=input_data, timeout=timeout) - exit_code = proc.returncode - if exit_code != consts.EXIT_SUCCESS: - raise FormatConversionError( - name, source_format, target_format, - f'Failed to execute (exit code: {exit_code}): ' - f'{stderr.decode(consts.DEFAULT_ENCODING)}', - ) - return stdout + # output goes to temporary files (deleted on close), not pipes, so nothing + # blocks on a full pipe and stderr is read only up to STDERR_LIMIT + with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr: + try: + # own process group (POSIX), so a timeout stops also the filters it started + proc = subprocess.Popen(args, cwd=workdir, stdin=subprocess.PIPE, + stdout=stdout, stderr=stderr, + start_new_session=True) + except FileNotFoundError as e: + raise FormatConversionError( + name, source_format, target_format, + f'Executable "{args[0]}" not found, is it installed?', + ) from e + try: + proc.communicate(input=input_data, timeout=timeout) + except subprocess.TimeoutExpired as e: + _kill(proc) + raise FormatConversionError( + name, source_format, target_format, + f'Exceeded the time limit of {timeout} seconds and was stopped', + ) from e + except BaseException: + _kill(proc) + raise + if proc.returncode != consts.EXIT_SUCCESS: + raise FormatConversionError( + name, source_format, target_format, + f'Failed to execute (exit code: {proc.returncode}): ' + f'{_read_tail(stderr, STDERR_LIMIT).decode(consts.DEFAULT_ENCODING, "replace")}', + ) + stdout.seek(0) + return stdout.read() + + +def _kill(proc: subprocess.Popen): + """Kill the process with everything it started, and reap it.""" + if sys.platform == 'win32': + proc.kill() + else: + # the group is still there, the leader has not been reaped yet + with contextlib.suppress(ProcessLookupError): + os.killpg(proc.pid, signal.SIGKILL) + if proc.stdin: + with contextlib.suppress(OSError): + proc.stdin.close() + proc.wait() + + +def _read_tail(file: typing.BinaryIO, limit: int) -> bytes: + size = file.seek(0, os.SEEK_END) + file.seek(max(0, size - limit)) + return file.read() class FormatConversionError(Exception): diff --git a/packages/dsw-templating/tests/test_template.py b/packages/dsw-templating/tests/test_template.py index aa9a90bc..fdb890f7 100644 --- a/packages/dsw-templating/tests/test_template.py +++ b/packages/dsw-templating/tests/test_template.py @@ -1,5 +1,9 @@ +import functools import io +import os import pathlib +import sys +import time import zipfile import pytest @@ -146,3 +150,65 @@ def test_docx_pagebreak_filter_without_extra(monkeypatch): monkeypatch.setitem(sys.modules, 'panflute', None) with pytest.raises(SystemExit, match=r'install dsw-templating\[docx\]'): docx_pagebreak.main() + + +FAKE_CONVERTER = ''' +import os, subprocess, sys, time +mode = sys.argv[1] +data = sys.stdin.buffer.read() +if mode == 'hang': + # a child that outlives a kill of this process alone, like a Pandoc filter + child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)']) + with open(sys.argv[2], 'w') as f: + f.write(f'{os.getpid()} {child.pid}') + time.sleep(60) +elif mode == 'fail': + sys.stderr.write('x' * 100000 + 'the end') + sys.exit(3) +sys.stdout.buffer.write(data.upper()) +''' + + +def _fake_pandoc(tmp_path, *args, timeout=None): + script = tmp_path / 'fake_converter.py' + script.write_text(FAKE_CONVERTER, encoding='utf-8') + settings = PandocSettings(command=[sys.executable, str(script), *args], timeout=timeout) + pandoc = Pandoc(settings, [], None) + return functools.partial(pandoc, source_format=FileFormats.HTML, + target_format=FileFormats.DOCX, metadata={}, + workdir=str(tmp_path)) + + +def _is_running(pid): + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + return True + + +def test_conversion_output(tmp_path): + assert _fake_pandoc(tmp_path, 'ok', timeout=30)(data=b'
') == b'' + assert _fake_pandoc(tmp_path, 'ok')(data=b'' * 100000) == b'' * 100000 + + +def test_conversion_failure_reports_end_of_stderr(tmp_path): + with pytest.raises(FormatConversionError, match=r'exit code: 3\): x+the end$') as e: + _fake_pandoc(tmp_path, 'fail')(data=b'') + assert len(e.value.message) < 70 * 1024 + + +@pytest.mark.skipif(sys.platform == 'win32', reason='process groups are POSIX') +def test_conversion_timeout_kills_process_group(tmp_path): + pids_file = tmp_path / 'pids' + with pytest.raises(FormatConversionError, + match='Pandoc failed to convert .* time limit of 1 seconds'): + _fake_pandoc(tmp_path, 'hang', str(pids_file), timeout=1)(data=b'') + pids = [int(pid) for pid in pids_file.read_text().split()] + deadline = time.monotonic() + 5 + # the orphaned child is reaped by init, give it a moment + while any(_is_running(pid) for pid in pids) and time.monotonic() < deadline: + time.sleep(0.05) + assert not any(_is_running(pid) for pid in pids) + # and the next conversion works + assert _fake_pandoc(tmp_path, 'ok', timeout=30)(data=b'') == b''