2018-12-16 20:22:20 +00:00
|
|
|
from os.path import join
|
2018-12-13 21:06:13 +00:00
|
|
|
from secrets import token_urlsafe
|
2018-12-13 21:44:46 +00:00
|
|
|
from collections import namedtuple
|
2018-12-13 22:00:54 +00:00
|
|
|
from abc import ABC, abstractmethod
|
2018-12-13 21:06:13 +00:00
|
|
|
|
2018-12-14 16:36:53 +00:00
|
|
|
from .pipe_reader_thread import PipeReaderThread
|
|
|
|
from .pipe_writer_thread import PipeWriterThread
|
2018-12-16 20:22:20 +00:00
|
|
|
from .pipe import Pipe
|
2018-12-13 21:06:13 +00:00
|
|
|
|
|
|
|
|
2018-12-13 22:00:54 +00:00
|
|
|
class PipeIOServer(ABC):
|
2018-12-13 21:06:13 +00:00
|
|
|
def __init__(self, in_pipe=None, out_pipe=None):
|
2018-12-16 22:28:33 +00:00
|
|
|
self._in_pipe, self._out_pipe = in_pipe, out_pipe
|
2018-12-16 18:04:51 +00:00
|
|
|
self._io_threads = None
|
2018-12-13 21:06:13 +00:00
|
|
|
self._create_pipes()
|
2018-12-16 18:04:51 +00:00
|
|
|
self._init_io_threads()
|
2018-12-13 21:06:13 +00:00
|
|
|
|
|
|
|
def _create_pipes(self):
|
|
|
|
if not self.in_pipe or not self.out_pipe:
|
|
|
|
pipe_id = token_urlsafe(6)
|
2018-12-16 22:28:33 +00:00
|
|
|
self._in_pipe = join('/tmp', f'in_pipe_{pipe_id}')
|
|
|
|
self._out_pipe = join('/tmp', f'out_pipe_{pipe_id}')
|
2018-12-16 20:22:20 +00:00
|
|
|
Pipe(self.in_pipe).recreate()
|
|
|
|
Pipe(self.out_pipe).recreate()
|
2018-12-13 21:06:13 +00:00
|
|
|
|
2018-12-16 22:28:33 +00:00
|
|
|
@property
|
|
|
|
def in_pipe(self):
|
|
|
|
return self._in_pipe
|
|
|
|
|
|
|
|
@property
|
|
|
|
def out_pipe(self):
|
|
|
|
return self._out_pipe
|
|
|
|
|
2018-12-16 18:04:51 +00:00
|
|
|
def _init_io_threads(self):
|
|
|
|
io_threads_dict = {
|
2018-12-16 18:16:01 +00:00
|
|
|
'reader': PipeReaderThread(self.in_pipe, self.handle_message),
|
2018-12-16 18:04:51 +00:00
|
|
|
'writer': PipeWriterThread(self.out_pipe)
|
|
|
|
}
|
|
|
|
IOThreadsTuple = namedtuple('IOThreadsTuple', sorted(io_threads_dict.keys()))
|
|
|
|
self._io_threads = IOThreadsTuple(**io_threads_dict)
|
|
|
|
|
2018-12-13 22:00:54 +00:00
|
|
|
@abstractmethod
|
2018-12-16 18:16:01 +00:00
|
|
|
def handle_message(self, message):
|
2018-12-13 22:00:54 +00:00
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def send(self, message):
|
2018-12-13 21:44:46 +00:00
|
|
|
self._io_threads.writer.write(message)
|
|
|
|
|
2018-12-13 21:06:13 +00:00
|
|
|
def run(self):
|
2018-12-13 21:44:46 +00:00
|
|
|
for thread in self._io_threads:
|
2018-12-13 21:06:13 +00:00
|
|
|
thread.start()
|
|
|
|
|
|
|
|
def stop(self):
|
2018-12-13 21:44:46 +00:00
|
|
|
for thread in self._io_threads:
|
2018-12-15 00:07:02 +00:00
|
|
|
if thread.isAlive():
|
|
|
|
thread.stop()
|
2018-12-16 20:22:20 +00:00
|
|
|
Pipe(self.in_pipe).remove()
|
|
|
|
Pipe(self.out_pipe).remove()
|