Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .cspell/dictionary.txt
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,6 @@ zenodo

# Language names (POT header examples)
Deutsch
getpid
killpg
pids
1 change: 1 addition & 0 deletions packages/dsw-document-worker/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
79 changes: 61 additions & 18 deletions packages/dsw-templating/dsw/templating/conversions.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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):
Expand Down
66 changes: 66 additions & 0 deletions packages/dsw-templating/tests/test_template.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import functools
import io
import os
import pathlib
import sys
import time
import zipfile

import pytest
Expand Down Expand Up @@ -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'<p/>') == b'<P/>'
assert _fake_pandoc(tmp_path, 'ok')(data=b'<p/>' * 100000) == b'<P/>' * 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'<p/>')
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'<p/>')
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'<p/>') == b'<P/>'
Loading