🚧 Timeouts & error handling on sockets

Also fix PushingTransportWrapper for SocketTransport
This commit is contained in:
Gina Häußge committed 2021-07-01 19:45:58 +02:00
1 parent c2d1e279ae
commit a707bfdee4
3 files changed
+111 -36

No files matched your search

+18 -6
View File
@@ -352,9 +352,7 @@ class SeparatorAwareTransportWrapper(TransportWrapper):
termlen = len(self.terminator)
timeout = serial.Timeout(timeout)
while not timeout.expired():
self._buffered += self.transport.read(self.transport.in_waiting)
def check_for_terminator():
# check for terminator, if it's there we have found our line
termpos = self._buffered.find(self.terminator)
if termpos >= 0:
@@ -362,8 +360,22 @@ class SeparatorAwareTransportWrapper(TransportWrapper):
line = self._buffered[: termpos + termlen]
del self._buffered[: termpos + termlen]
received = bytes(line)
self.notify_listeners("on_transport_log_received_data", self, received)
return received
else:
return None
line = check_for_terminator()
if line is not None:
self.notify_listeners("on_transport_log_received_data", self, line)
return line
while not timeout.expired():
self._buffered += self.transport.read(self.transport.in_waiting)
line = check_for_terminator()
if line is not None:
self.notify_listeners("on_transport_log_received_data", self, line)
return line
if timeout.expired():
break
@@ -437,9 +449,9 @@ class PushingTransportWrapper(TransportWrapper):
self.notify_listeners("on_transport_data_pushed", self, data)
except TimeoutTransportException as ex:
self.notify_listeners("on_transport_data_exception", self, ex)
except Exception:
except Exception as ex:
if self._receiver_active:
raise
self.notify_listeners("on_transport_data_exception", self, ex)
def __str__(self):
return f"PushingTransportWrapper({self.transport})"
+64 -17
View File
@@ -3,8 +3,11 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
import select
import socket
import time
from octoprint.comm.transport import Transport
from flask_babel import gettext
from octoprint.comm.transport import TimeoutTransportException, Transport
from octoprint.settings.parameters import IntegerType, TextType
@@ -13,9 +16,35 @@ class SocketTransport(Transport):
name = "Socket Connection"
key = "socket"
BUFSIZE = 4096
@classmethod
def get_connection_options(cls):
return [TextType("host", "Host"), IntegerType("port", "Port", min=1, max=65535)]
return [
TextType("host", "Host"),
IntegerType("port", "Port", min=1, max=65535),
] + cls.get_common_connection_options()
@classmethod
def get_common_connection_options(cls):
return [
IntegerType(
"read_timeout",
gettext("Read Timeout"),
min=1,
unit="sec",
default=2,
advanced=True,
),
IntegerType(
"write_timeout",
gettext("Write Timeout"),
min=1,
unit="sec",
default=10,
advanced=True,
),
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -24,9 +53,13 @@ class SocketTransport(Transport):
def create_connection(self, **kwargs):
result = self.create_socket(**kwargs)
self._socket.setblocking(False)
self.set_current_args(**kwargs)
return result
def in_waiting(self):
return 0 # we don't know how many bytes are waiting, we'll ignore size on do_read
def drop_connection(self, wait=True):
try:
self._socket.close()
@@ -36,20 +69,31 @@ class SocketTransport(Transport):
return False
def do_read(self, size=None, timeout=None):
if size is None:
size = 16
if timeout is None:
timeout = self._args.get("read_timeout", 2)
if timeout is not None:
self._socket.setblocking(0)
ready = select.select([self._socket], [], [], timeout)
if ready[0]:
return self._socket.recv(size)
raise socket.timeout()
else:
return self._socket.recv(size)
# size is unused here, but is used by other transports
ready = select.select([self._socket], [], [], timeout)
if not ready[0]:
raise TimeoutTransportException()
return self._socket.recv(self.BUFSIZE)
def do_write(self, data):
self._socket.sendall(data)
start = time.monotonic()
timeout = self._args.get("write_timeout", 10)
total_sent = 0
while total_sent < len(data):
ready = select.select(
[], [self._socket], [], timeout - (time.monotonic() - start)
)
if not ready[1]:
raise TimeoutTransportException()
sent = self._socket.send(data[total_sent:])
if sent == 0:
raise OSError("Connection closed")
total_sent += sent
def create_socket(self, **kwargs):
raise NotImplementedError()
@@ -71,9 +115,12 @@ class TCPSocketTransport(SocketTransport):
@classmethod
def get_connection_options(cls):
return [TextType("host", "Host"), IntegerType("port", "Port", min=1, max=65535)]
return [
TextType("host", "Host"),
IntegerType("port", "Port", min=1, max=65535),
] + cls.get_common_connection_options()
def create_socket(self, host=None, port=None):
def create_socket(self, host=None, port=None, **kwargs):
if host is None:
raise ValueError("host must not be None")
if port is None:
@@ -98,9 +145,9 @@ if hasattr(socket, "AF_UNIX"):
@classmethod
def get_connection_options(cls):
return [TextType("path", "Path")]
return [TextType("path", "Path")] + cls.get_common_connection_options()
def create_socket(self, path=None):
def create_socket(self, path=None, **kwargs):
if path is None:
raise ValueError("path must not be None")
@@ -176,8 +176,10 @@ class VirtualPrinterPlugin(
try:
while True:
chunk = self._do_read(self.CHUNK_SIZE)
print(repr(chunk))
try:
chunk = self._do_read(self.CHUNK_SIZE)
except socket.timeout:
continue
buffered.extend(chunk)
@@ -188,6 +190,8 @@ class VirtualPrinterPlugin(
line = buffered[: termpos + termlen]
del buffered[: termpos + termlen]
received = bytes(line)
print(f"<<< {received.rstrip()}")
self.incoming.put(received)
except Exception:
self.close()
@@ -200,6 +204,7 @@ class VirtualPrinterPlugin(
try:
self._do_write(to_bytes(line, encoding="ascii", errors="replace"))
print(f">>> {line.rstrip()}")
except Exception:
self.close()
raise
@@ -217,11 +222,16 @@ class VirtualPrinterPlugin(
super().__init__(*args, **kwargs)
def _do_read(self, size):
select.select([self._socket], [], [])
ready = select.select([self._socket], [], [], 2)
if self._socket not in ready[0]:
raise socket.timeout()
return self._socket.recv(size)
def _do_write(self, data):
try:
ready = select.select([], [self._socket], [], 10)
if self._socket not in ready[1]:
raise socket.timeout()
self._socket.sendall(data)
except Exception:
self.close()
@@ -237,11 +247,13 @@ class VirtualPrinterPlugin(
with socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) as s:
s.bind((host, port))
s.listen()
conn, addr = s.accept()
print(f"Connection from {addr}")
with conn:
virtual = SocketVirtualPrinterWrapper(conn, settings, datafolder)
virtual.wait()
while True:
conn, addr = s.accept()
print(f"Connection from {addr}")
with conn:
virtual = SocketVirtualPrinterWrapper(conn, settings, datafolder)
virtual.wait()
print(f"Connection closed from {addr}")
commands = [
tcp_command,
@@ -258,11 +270,15 @@ class VirtualPrinterPlugin(
with socket.socket(family=socket.AF_UNIX, type=socket.SOCK_STREAM) as s:
s.bind(path)
s.listen()
conn, addr = s.accept()
print(f"Connection from {addr}")
with conn:
virtual = SocketVirtualPrinterWrapper(conn, settings, datafolder)
virtual.wait()
while True:
conn, addr = s.accept()
print(f"Connection from {addr}")
with conn:
virtual = SocketVirtualPrinterWrapper(
conn, settings, datafolder
)
virtual.wait()
print(f"Connection closed from {addr}")
commands.append(uds_command)