mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-25 17:36:18 -05:00
Reworking Downloader.process_runner to use real stdout/stderr files to avoid issue with pipes being truncated.
This commit is contained in:
parent
8825bfad1a
commit
0784f740bb
6 changed files with 96 additions and 97 deletions
|
|
@ -3,6 +3,7 @@ import json
|
|||
import pathlib
|
||||
import tempfile
|
||||
from abc import ABC
|
||||
from json import JSONDecodeError
|
||||
from typing import List, Tuple, Iterable
|
||||
|
||||
from selenium import webdriver
|
||||
|
|
@ -71,41 +72,38 @@ class ArchiveDownloader(Downloader, ABC):
|
|||
|
||||
async def do_singlefile(self, download: Download) -> Tuple[bytes, dict]:
|
||||
"""Create a Singlefile from the archive's URL."""
|
||||
with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as output:
|
||||
output = pathlib.Path(output.name)
|
||||
cmd = ('/usr/bin/nice', '-n15', # Nice above map importing, but very low priority.
|
||||
str(SINGLE_FILE_BIN),
|
||||
'--browser-executable-path', CHROMIUM,
|
||||
'--browser-args', '["--no-sandbox"]',
|
||||
'--user-agent', USER_AGENT,
|
||||
download.url,
|
||||
output,
|
||||
)
|
||||
return_code, logs, stdout = await self.process_runner(
|
||||
download.id,
|
||||
download.url,
|
||||
cmd,
|
||||
pathlib.Path('/home/wrolpi'),
|
||||
)
|
||||
cmd = ('/usr/bin/nice', '-n15', # Nice above map importing, but very low priority.
|
||||
str(SINGLE_FILE_BIN),
|
||||
'--browser-executable-path', CHROMIUM,
|
||||
'--browser-args', '["--no-sandbox"]',
|
||||
'--user-agent', USER_AGENT,
|
||||
'--dump-content',
|
||||
'--load-deferred-images-dispatch-scroll-event',
|
||||
download.url,
|
||||
)
|
||||
return_code, logs, stdout = await self.process_runner(
|
||||
download.id,
|
||||
download.url,
|
||||
cmd,
|
||||
pathlib.Path('/home/wrolpi'),
|
||||
)
|
||||
|
||||
stdout = stdout.decode()
|
||||
stderr = logs['stderr'].decode()
|
||||
log_output = stderr or stdout or 'No stderr or stdout!'
|
||||
stderr = logs['stderr'].decode()
|
||||
log_output = stderr or stdout.decode() or 'No stderr or stdout!'
|
||||
|
||||
if return_code != 0:
|
||||
e = ChildProcessError(log_output[:1000])
|
||||
raise RuntimeError(f'Archive singlefile exited with {return_code}') from e
|
||||
if return_code != 0:
|
||||
e = ChildProcessError(log_output[:1000])
|
||||
raise RuntimeError(f'singlefile exited with {return_code}') from e
|
||||
|
||||
content = output.read_bytes() if output.is_file() else ''
|
||||
if not content:
|
||||
e = ChildProcessError(log_output[:1000])
|
||||
raise RuntimeError(f'Singlefile created was empty: {download.url}') from e
|
||||
if not stdout:
|
||||
e = ChildProcessError(log_output[:1000])
|
||||
raise RuntimeError(f'Singlefile created was empty: {download.url}') from e
|
||||
|
||||
if SINGLEFILE_HEADER.encode() not in content:
|
||||
e = ChildProcessError(log_output[:1000])
|
||||
raise RuntimeError(f'Singlefile created was invalid: {download.url}') from e
|
||||
if SINGLEFILE_HEADER.encode() not in stdout:
|
||||
e = ChildProcessError(log_output[:1000])
|
||||
raise RuntimeError(f'Singlefile created was invalid: {download.url}') from e
|
||||
|
||||
return content, logs
|
||||
return stdout, logs
|
||||
|
||||
async def do_readability(self, download: Download, html: bytes) -> dict:
|
||||
"""Extract the readability dict from the provided HTML."""
|
||||
|
|
@ -121,9 +119,11 @@ class ArchiveDownloader(Downloader, ABC):
|
|||
pathlib.Path('/home/wrolpi'),
|
||||
)
|
||||
if return_code == 0:
|
||||
if not stdout:
|
||||
raise RuntimeError('readability stdout was empty')
|
||||
try:
|
||||
readability = json.loads(stdout)
|
||||
except TypeError:
|
||||
except TypeError or JSONDecodeError:
|
||||
# JSON was invalid.
|
||||
e = ChildProcessError(stdout.decode() if stdout else 'No stdout')
|
||||
if logs and (stderr := logs.get('stderr')):
|
||||
|
|
|
|||
|
|
@ -354,14 +354,10 @@ class VideoDownloader(Downloader, ABC):
|
|||
video.source_id = entry['id']
|
||||
video.channel_id = channel_id
|
||||
video_id, video_info_json_path = video.id, video.info_json_path
|
||||
if video_info_json_path:
|
||||
if new_info_json := video.clean_info_json():
|
||||
video.replace_info_json(new_info_json)
|
||||
if video_info_json_path and (new_info_json := video.clean_info_json()):
|
||||
video.replace_info_json(new_info_json, clean=False)
|
||||
session.commit()
|
||||
|
||||
if video_info_json_path:
|
||||
format_json_file(video_info_json_path)
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
# Second session is started because SQLAlchemy will forget what we have done.
|
||||
video = Video.get_by_id(video_id, session)
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ from wrolpi.files.lib import refresh_files, split_path_stem_and_suffix, move
|
|||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.media_path import MediaPathType
|
||||
from wrolpi.tags import Tag, TagFile, save_tags_config
|
||||
from wrolpi.vars import PYTEST, DELETED_VIDEO_KEYS
|
||||
from wrolpi.vars import PYTEST, VIDEO_INFO_JSON_KEYS_TO_CLEAN
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
|
|
@ -505,15 +505,21 @@ class Video(ModelHelper, Base):
|
|||
"""Remove large and mostly useless data in the info_json."""
|
||||
info_json_contents = info_json_contents or self.get_info_json()
|
||||
if info_json_contents:
|
||||
for key in DELETED_VIDEO_KEYS:
|
||||
for key in VIDEO_INFO_JSON_KEYS_TO_CLEAN:
|
||||
info_json_contents.pop(key, None)
|
||||
return info_json_contents
|
||||
|
||||
def replace_info_json(self, info_json: dict):
|
||||
def replace_info_json(self, info_json: dict, clean: bool = True, format_: bool = True):
|
||||
"""Replace the info json file with the new json dict. Handles adding new info_json file, if necessary."""
|
||||
info_json_path = self.info_json_path or self.video_path.with_suffix('.info.json')
|
||||
info_json = self.clean_info_json(info_json)
|
||||
info_json = json.dumps(info_json, indent=2)
|
||||
if clean:
|
||||
info_json = self.clean_info_json(info_json)
|
||||
|
||||
if format_:
|
||||
info_json = json.dumps(info_json, indent=2, sort_keys=True)
|
||||
else:
|
||||
info_json = json.dumps(info_json)
|
||||
|
||||
replace_file(info_json_path, info_json, missing_ok=True)
|
||||
|
||||
if not self.info_json_path:
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import logging
|
|||
import multiprocessing
|
||||
import os
|
||||
import pathlib
|
||||
import tempfile
|
||||
import traceback
|
||||
from abc import ABC
|
||||
from dataclasses import dataclass, field
|
||||
|
|
@ -25,9 +26,8 @@ from sqlalchemy.sql import Delete
|
|||
|
||||
from wrolpi import flags
|
||||
from wrolpi.api_utils import api_app, perpetual_signal
|
||||
from wrolpi.cmd import pid_is_running
|
||||
from wrolpi.common import Base, ModelHelper, logger, wrol_mode_check, zig_zag, ConfigFile, WROLPI_CONFIG, \
|
||||
wrol_mode_enabled, background_task
|
||||
from wrolpi.common import Base, ModelHelper, logger, wrol_mode_check, zig_zag, ConfigFile, \
|
||||
wrol_mode_enabled, background_task, get_wrolpi_config
|
||||
from wrolpi.dates import TZDateTime, now, Seconds
|
||||
from wrolpi.db import get_db_session, get_db_curs, optional_session
|
||||
from wrolpi.errors import InvalidDownload, UnrecoverableDownloadError, UnknownDownload
|
||||
|
|
@ -298,60 +298,51 @@ class Downloader:
|
|||
str_cmd = " ".join([str(i) for i in cmd])
|
||||
logger.info(f'{self} launching download process with args: {str_cmd}')
|
||||
start = now()
|
||||
proc = await asyncio.create_subprocess_exec(*cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
cwd=cwd,
|
||||
**kwargs)
|
||||
pid = proc.pid
|
||||
# Use temporary files to prevent trucating of stdout/stderr.
|
||||
with tempfile.NamedTemporaryFile() as stdout, tempfile.NamedTemporaryFile() as stderr:
|
||||
stdout, stderr = pathlib.Path(stdout.name), pathlib.Path(stderr.name)
|
||||
with stdout.open('wb') as stdout_fh, stderr.open('wb') as stderr_fh:
|
||||
# stdout/stderr is written to real files.
|
||||
proc = await asyncio.create_subprocess_exec(*cmd,
|
||||
stdout=stdout_fh,
|
||||
stderr=stderr_fh,
|
||||
cwd=cwd,
|
||||
**kwargs)
|
||||
pid = proc.pid
|
||||
|
||||
# Timeout can be any positive integer. Global download timeout takes precedence, unless it is 0.
|
||||
# A timeout of 0 means the download will never be killed.
|
||||
timeout = WROLPI_CONFIG.download_timeout or timeout or self.timeout
|
||||
logger.debug(f'{self} launched download process {pid=} {timeout=} for {url}')
|
||||
# Timeout can be any positive integer. Global download timeout takes precedence, unless it is 0.
|
||||
# A timeout of 0 means the download will never be killed.
|
||||
timeout = get_wrolpi_config().download_timeout or timeout or self.timeout
|
||||
logger.debug(f'{self} launched download process {pid=} {timeout=} for {url}')
|
||||
|
||||
stdout, stderr = b'', b''
|
||||
try:
|
||||
while True:
|
||||
task = asyncio.Task(proc.communicate())
|
||||
done, pending = await asyncio.wait([task, ], timeout=1)
|
||||
# Cancel communicate.
|
||||
if pending:
|
||||
pending.pop().cancel()
|
||||
if done:
|
||||
# Process finished, get the result of proc.communicate().
|
||||
stdout, stderr = done.pop().result()
|
||||
break
|
||||
if proc.returncode:
|
||||
# Process died.
|
||||
stdout, stderr = await proc.communicate()
|
||||
break
|
||||
while True:
|
||||
# Calculate the seconds since the process started.
|
||||
elapsed = int((now() - start).total_seconds())
|
||||
|
||||
if not pid_is_running(pid):
|
||||
logger.debug(f'Process is no longer running! {str_cmd}')
|
||||
break
|
||||
# Check if the cancel event is set or if the timeout is reached
|
||||
if download_manager.download_is_killed(download_id):
|
||||
logger.warning(f'Killing download {pid=}, {elapsed} seconds elapsed.')
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
break
|
||||
if timeout and elapsed > timeout:
|
||||
# TODO this logic should be handled by the Download Manager.
|
||||
download_manager.kill_download(download_id)
|
||||
continue
|
||||
|
||||
elapsed = (now() - start).total_seconds()
|
||||
if timeout and elapsed > timeout:
|
||||
logger.warning(f'Download has exceeded its timeout {elapsed=}')
|
||||
download_manager.kill_download(download_id)
|
||||
try:
|
||||
# Wait for the process to finish.
|
||||
await asyncio.wait_for(proc.wait(), timeout=1)
|
||||
break
|
||||
except TimeoutError:
|
||||
# Subprocess has not yet finished, loop again and wait for it to finish.
|
||||
continue
|
||||
|
||||
if download_manager.download_is_killed(download_id):
|
||||
logger.warning(f'Killing download {pid=}, {elapsed} seconds elapsed.')
|
||||
proc.kill()
|
||||
break
|
||||
except Exception as e:
|
||||
logger.error(f'{self}.process_runner had a download error', exc_info=e)
|
||||
raise
|
||||
finally:
|
||||
# Output all logs from the process.
|
||||
# TODO is there a way to stream this output while the process is running?
|
||||
stdout_len = len(stdout)
|
||||
stderr_len = len(stderr)
|
||||
# Read stdout/stderr files.
|
||||
stdout, stderr = stdout.read_bytes(), stderr.read_bytes()
|
||||
stdout_len, stderr_len = len(stdout) if stdout else 0, len(stderr) if stderr else 0
|
||||
logger.debug(f'Download exited with {proc.returncode} and stdout={stdout_len} stderr={stderr_len}')
|
||||
logs = {'stdout': stdout, 'stderr': stderr}
|
||||
|
||||
return proc.returncode, logs, stdout
|
||||
return proc.returncode, dict(stdout=stdout, stderr=stderr), stdout
|
||||
|
||||
@staticmethod
|
||||
async def cancel_wrapper(coro: Coroutine, download: Download):
|
||||
|
|
|
|||
|
|
@ -279,24 +279,30 @@ async def test_process_runner_timeout(async_client, test_session, test_directory
|
|||
# Default timeout of 3 seconds.
|
||||
downloader = Downloader('downloader', timeout=3)
|
||||
|
||||
# Sleep for 8 seconds really takes 8 seconds.
|
||||
start = datetime.now()
|
||||
await downloader.process_runner(1, 'https://example.com', ('sleep', '8'), test_directory, timeout=10)
|
||||
elapsed = datetime.now() - start
|
||||
assert elapsed.total_seconds() >= 8
|
||||
|
||||
# Default timeout is obeyed.
|
||||
start = datetime.now()
|
||||
await downloader.process_runner(1, 'https://example.com', ('sleep', '8'), test_directory)
|
||||
elapsed = datetime.now() - start
|
||||
assert 3 < elapsed.total_seconds() < 4
|
||||
assert 3 < elapsed.total_seconds() < 5
|
||||
|
||||
# One-off timeout is obeyed.
|
||||
start = datetime.now()
|
||||
await downloader.process_runner(2, 'https://example.com', ('sleep', '8'), test_directory, timeout=1)
|
||||
elapsed = datetime.now() - start
|
||||
assert 1 < elapsed.total_seconds() < 2
|
||||
assert 1 < elapsed.total_seconds() < 3
|
||||
|
||||
# Global timeout is obeyed.
|
||||
get_wrolpi_config().download_timeout = 3
|
||||
start = datetime.now()
|
||||
await downloader.process_runner(3, 'https://example.com', ('sleep', '8'), test_directory)
|
||||
elapsed = datetime.now() - start
|
||||
assert 2 < elapsed.total_seconds() < 4
|
||||
assert 2 < elapsed.total_seconds() < 5
|
||||
|
||||
|
||||
GOOD_SCRIPT = '''#! /usr/bin/env bash
|
||||
|
|
|
|||
|
|
@ -97,7 +97,7 @@ FILE_MAX_TEXT_SIZE = int(os.environ.get('FILE_MAX_TEXT_SIZE', 100_000))
|
|||
|
||||
VIDEO_COMMENTS_FETCH_COUNT = int(os.environ.get('VIDEO_COMMENTS_FETCH_COUNT', 80))
|
||||
YTDLP_CACHE_DIR = os.environ.get('YTDLP_CACHE_DIR', '/tmp/ytdlp_cache')
|
||||
DELETED_VIDEO_KEYS = list_var('DELETED_VIDEO_KEYS', 'automatic_captions,formats')
|
||||
VIDEO_INFO_JSON_KEYS_TO_CLEAN = list_var('DELETED_VIDEO_KEYS', 'automatic_captions,formats,thumbnails')
|
||||
|
||||
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.366'
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue