Improve CommandEventHandler error detection (avoid polling)

This commit is contained in:
Kristóf Tóth 2019-05-13 11:17:30 +02:00
parent ca5be9d848
commit 1617761184

View File

@ -6,7 +6,6 @@ from os import getpgid, killpg
from os.path import join from os.path import join
from signal import SIGTERM from signal import SIGTERM
from secrets import token_urlsafe from secrets import token_urlsafe
from time import sleep
from threading import Thread from threading import Thread
from contextlib import suppress from contextlib import suppress
@ -113,26 +112,22 @@ class CommandEventHandler(PipeIOEventHandler):
stdin=self._proc_stdin, stdout=self._proc_stdout, stderr=PIPE, stdin=self._proc_stdin, stdout=self._proc_stdout, stderr=PIPE,
start_new_session=True start_new_session=True
) )
self._poll_check_proc_thread = self._start_poll_check_proc() self._monitor_proc_thread = self._start_monitor_proc()
def _generate_tempfilename(self): def _generate_tempfilename(self):
# pylint: disable=no-self-use # pylint: disable=no-self-use
random_filename = partial(token_urlsafe, 10) random_filename = partial(token_urlsafe, 10)
return join('/tmp', f'{type(self).__name__}.{random_filename()}') return join('/tmp', f'{type(self).__name__}.{random_filename()}')
def _start_poll_check_proc(self): def _start_monitor_proc(self):
thread = Thread(target=self._poll_check_proc, daemon=True) thread = Thread(target=self._monitor_proc, daemon=True)
thread.start() thread.start()
return thread return thread
@terminate_process_on_failure @terminate_process_on_failure
def _poll_check_proc(self): def _monitor_proc(self):
while True: return_code = self._proc.wait()
self.check_proc() if return_code != 0:
sleep(1)
def check_proc(self):
if self._proc.poll() is not None:
_, stderr = self._proc.communicate() _, stderr = self._proc.communicate()
raise RuntimeError(f'Subprocess failed: {stderr.decode()}') raise RuntimeError(f'Subprocess failed: {stderr.decode()}')