2019-08-05 15:28:04 +00:00
|
|
|
# pylint: disable=redefined-builtin,too-many-instance-attributes
|
|
|
|
from contextlib import contextmanager
|
|
|
|
from os import O_NONBLOCK, O_RDONLY, open, fdopen, close, write, pipe
|
2018-12-14 16:36:53 +00:00
|
|
|
from threading import Thread
|
2019-08-05 15:28:04 +00:00
|
|
|
from select import select
|
2018-12-14 23:32:29 +00:00
|
|
|
|
|
|
|
from .terminate_process_on_failure import terminate_process_on_failure
|
2018-12-14 16:36:53 +00:00
|
|
|
|
|
|
|
|
|
|
|
class PipeReaderThread(Thread):
|
2019-03-28 15:25:53 +00:00
|
|
|
def __init__(self, pipe_path, stop_event, message_handler):
|
2019-05-07 15:16:43 +00:00
|
|
|
super().__init__(daemon=True)
|
2018-12-14 16:36:53 +00:00
|
|
|
self._message_handler = message_handler
|
|
|
|
self._pipe_path = pipe_path
|
2019-08-05 15:28:04 +00:00
|
|
|
self._read_fd, self._read_fp = None, None
|
|
|
|
self._stop_signal_rfd, self._stop_signal_wfd = pipe()
|
|
|
|
self._msg_buf = b''
|
2019-03-28 15:25:53 +00:00
|
|
|
self._stop_event = stop_event
|
2018-12-14 16:36:53 +00:00
|
|
|
|
2018-12-14 23:32:29 +00:00
|
|
|
@terminate_process_on_failure
|
2018-12-14 16:36:53 +00:00
|
|
|
def run(self):
|
2019-08-05 15:28:04 +00:00
|
|
|
with self._open():
|
2019-03-28 15:25:53 +00:00
|
|
|
while True:
|
2019-08-05 15:28:04 +00:00
|
|
|
can_read, _, _ = select([self._read_fd, self._stop_signal_rfd], [], [])
|
|
|
|
if self._stop_signal_rfd in can_read:
|
2019-03-28 15:25:53 +00:00
|
|
|
self._stop_event.set()
|
|
|
|
break
|
2019-08-05 15:28:04 +00:00
|
|
|
for msg in iter(self._read_fp.readline, b''):
|
|
|
|
self._msg_buf += msg
|
|
|
|
if self._msg_buf.endswith(b'\n'):
|
|
|
|
self._message_handler(self._msg_buf[:-1])
|
|
|
|
self._msg_buf = b''
|
2018-12-14 16:36:53 +00:00
|
|
|
|
2019-08-05 15:28:04 +00:00
|
|
|
@contextmanager
|
2019-05-02 21:07:32 +00:00
|
|
|
def _open(self):
|
2019-08-05 15:28:04 +00:00
|
|
|
self._read_fd = open(self._pipe_path, O_RDONLY | O_NONBLOCK)
|
|
|
|
self._read_fp = fdopen(self._read_fd, 'rb')
|
|
|
|
yield
|
|
|
|
self._read_fp.close()
|
|
|
|
close(self._stop_signal_rfd)
|
|
|
|
close(self._stop_signal_wfd)
|
|
|
|
|
2019-05-02 21:07:32 +00:00
|
|
|
|
2018-12-14 16:36:53 +00:00
|
|
|
def stop(self):
|
2019-08-05 15:28:04 +00:00
|
|
|
if self.is_alive():
|
2019-05-03 20:00:23 +00:00
|
|
|
self._unblock()
|
2018-12-14 16:36:53 +00:00
|
|
|
self.join()
|
2019-03-28 15:25:53 +00:00
|
|
|
|
2019-05-03 15:31:57 +00:00
|
|
|
def _unblock(self):
|
2019-08-05 15:28:04 +00:00
|
|
|
write(self._stop_signal_wfd, b'1')
|