2018-12-08 13:11:01 +00:00
|
|
|
import os
|
2018-12-07 23:34:59 +00:00
|
|
|
import socket
|
2018-12-07 20:35:34 +00:00
|
|
|
import socketserver
|
|
|
|
import threading
|
2018-12-07 20:44:31 +00:00
|
|
|
|
2018-12-07 20:35:34 +00:00
|
|
|
import ujson
|
2018-12-08 14:36:37 +00:00
|
|
|
from ipc_unix.utils import NEW_LINE, read_payload
|
2018-12-07 20:35:34 +00:00
|
|
|
|
|
|
|
|
2018-12-08 14:23:16 +00:00
|
|
|
class Client:
|
|
|
|
def __init__(self, socket_path):
|
|
|
|
self.socket_path = socket_path
|
|
|
|
|
|
|
|
def send(self, data: dict):
|
|
|
|
with socket.socket(socket.AF_UNIX, type=socket.SOCK_STREAM) as sock:
|
|
|
|
sock.connect(self.socket_path)
|
2018-12-08 14:36:37 +00:00
|
|
|
sock.sendall(ujson.dumps(data).encode() + NEW_LINE)
|
2018-12-08 14:23:16 +00:00
|
|
|
return read_payload(sock)[0]
|
2018-12-07 23:34:59 +00:00
|
|
|
|
|
|
|
|
2018-12-07 20:35:34 +00:00
|
|
|
class RequestHandler(socketserver.BaseRequestHandler):
|
2018-12-08 01:12:34 +00:00
|
|
|
def handle_request(self, request: dict):
|
2018-12-07 20:35:34 +00:00
|
|
|
raise NotImplementedError("Failed to override `handle_request`")
|
|
|
|
|
|
|
|
def handle(self):
|
2018-12-08 01:12:34 +00:00
|
|
|
data = read_payload(self.request)[0]
|
2018-12-07 20:35:34 +00:00
|
|
|
response = self.handle_request(data)
|
|
|
|
self.request.sendall(ujson.dumps(response).encode())
|
|
|
|
|
|
|
|
|
|
|
|
class Server:
|
|
|
|
def __init__(self, socket_path):
|
|
|
|
class InstanceRequestHandler(RequestHandler):
|
|
|
|
handle_request = self.handle_request
|
|
|
|
|
2018-12-08 13:09:38 +00:00
|
|
|
self.socket_path = socket_path
|
2018-12-08 13:11:01 +00:00
|
|
|
self.server = socketserver.UnixStreamServer(
|
|
|
|
self.socket_path, InstanceRequestHandler
|
|
|
|
)
|
2018-12-07 20:35:34 +00:00
|
|
|
|
|
|
|
def serve_forever(self):
|
|
|
|
self.server.serve_forever()
|
|
|
|
|
|
|
|
def serve_in_thread(self):
|
|
|
|
thread = threading.Thread(target=self.serve_forever)
|
|
|
|
thread.start()
|
|
|
|
return thread
|
|
|
|
|
|
|
|
def close(self):
|
2018-12-08 13:07:51 +00:00
|
|
|
self.server.shutdown()
|
2018-12-07 20:35:34 +00:00
|
|
|
self.server.server_close()
|
2018-12-08 13:09:38 +00:00
|
|
|
os.remove(self.socket_path)
|
2018-12-07 20:35:34 +00:00
|
|
|
|
2018-12-08 01:12:34 +00:00
|
|
|
def handle_request(self, request: dict):
|
2018-12-07 20:35:34 +00:00
|
|
|
raise NotImplementedError("Must override `handle_request`")
|