diff options
author | Markus Otto <otto@fs.tum.de> | 2015-08-22 19:15:22 +0200 |
---|---|---|
committer | MaZderMind <git@mazdermind.de> | 2015-08-31 20:02:04 +0200 |
commit | 46aace37db5c035a6d6b432db261dc7c417456f4 (patch) | |
tree | cc98a569c8c02491ce59cbf5b9a5613c96fd78b2 /voctocore/lib/controlserver.py | |
parent | 5c243f1cac5cc489f3bbb821ab5064d9edf7d449 (diff) |
make protocol work, some gui stuff
Diffstat (limited to 'voctocore/lib/controlserver.py')
-rw-r--r-- | voctocore/lib/controlserver.py | 173 |
1 files changed, 87 insertions, 86 deletions
diff --git a/voctocore/lib/controlserver.py b/voctocore/lib/controlserver.py index 1a75a49..4e95e46 100644 --- a/voctocore/lib/controlserver.py +++ b/voctocore/lib/controlserver.py @@ -1,5 +1,6 @@ #!/usr/bin/python3 import socket, logging, traceback +from queue import Queue from gi.repository import GObject from lib.commands import ControlServerCommands @@ -11,113 +12,113 @@ class ControlServer(TCPMultiConnection): self.log = logging.getLogger('ControlServer') super().__init__(port=9999) + self.command_queue = Queue() + self.commands = ControlServerCommands(pipeline) + GObject.idle_add(self.on_loop) + def on_accepted(self, conn, addr): '''Asynchronous connection listener. Starts a handler for each connection.''' - self.log.debug('Setting GObject io-watch on Connection') - GObject.io_add_watch(conn, GObject.IO_IN, self.on_data) - - def on_data(self, conn, *args): - '''Asynchronous connection handler. Processes each line from the socket.''' - # construct a file-like object fro mthe socket - # to be able to read linewise and in utf-8 - filelike = conn.makefile('rw') + GObject.io_add_watch(conn, GObject.IO_IN, self.on_data, ['']) + GObject.io_add_watch(conn, GObject.IO_OUT, self.on_write) - # read a line from the socket - line = '' + def on_data(self, conn, _, leftovers, *args): + '''Asynchronous connection handler. Pushes data from socket + into command queue linewise''' try: - line = filelike.readline().strip() - except Exception as e: - self.log.warn("Can't read from socket: %s", e) - - # no data = remote closed connection - if len(line) == 0: - self.close_connection(conn) - return False - - # 'quit' = remote wants us to close the connection - if line == 'quit': - self.log.info("Client asked us to close the Connection") - self.close_connection(conn) - return False - - # process the received line - success, msg = self.processLine(conn, line) - - # success = False -> error - if success == False: - # on error-responses the message is mandatory - if msg is None: - msg = '<no message>' - - # respond with 'error' and the message - filelike.write('error '+msg+'\n') - self.log.info("Function-Call returned an Error: %s", msg) + while True: + try: + leftovers.append(conn.recv(4096).decode(errors='replace')) + if len(leftovers[-1]) == 0: + self.log.info("Socket was closed") + self.close_connection(conn) + return False + except UnicodeDecodeError as e: + continue + except BlockingIOError as e: + pass + + data = "".join(leftovers) + leftovers.clear() + + lines = data.split('\n') + for line in lines[:-1]: + self.log.debug("Got line: %r", line) + + line = line.strip() + # TODO: move quit to on_loop + # 'quit' = remote wants us to close the connection + if line == 'quit': + self.log.info("Client asked us to close the Connection") + self.close_connection(conn) + return False + + self.command_queue.put((line, conn)) + + self.log.debug("Remaining %r", lines[-1]) + leftovers.append(lines[-1]) + return True - # keep on listening on that connection + def on_loop(self): + '''Command handler. Processes commands in the command queue whenever + nothing else is happening (registered as GObject idle callback)''' + if self.command_queue.empty(): return True + line, requestor = self.command_queue.get() - # success = True and not message - if msg is None: - # respond with a simple 'ok' - filelike.write('ok\n') - else: - # respond with the returned message - filelike.write('ok '+msg+'\n') - - return True - - def processLine(self, conn, line): - # split line into command and optional args words = line.split() command = words[0] args = words[1:] - # log function-call as parsed - self.log.info("Read Function-Call from %s: %s( %s )", conn.getpeername(), command, args) + try: + f = self.commands.fetch(command) + message, send_signals = f(*args) + response = "ok %s\n" % message - # check that the function-call is a known Command - if not hasattr(self.commands, command): - return False, 'unknown command %s' % command + except Exception as e: + message = str(e) or "<no message>" + response = "error %s\n" % message + else: + if send_signals: + signal = "signal %s\n" % line + for conn, queue in self.currentConnections.items(): + if conn == requestor: + continue + queue.put(signal) - try: - # fetch the function-pointer - f = getattr(self.commands, command) + finally: + self.currentConnections[requestor].put(response) - # call the function - ret = f(*args) + return True - # signal method call to all other connected clients - # only signal set_* commands - if command.split('_')[0] in ["set", "message"]: - self.signal(conn, command, args) + def on_write(self, conn, *args): + # TODO: on_loop() is not called as soon as there is a writable socket + self.on_loop() - # if it returned an iterable, probably (Success, Message), pass that on - if hasattr(ret, '__iter__'): - return ret - else: - # otherwise construct a tuple - return (ret, None) + try: + queue = self.currentConnections[conn] + except KeyError: + return False + if queue.empty(): + return True + message = queue.get() + try: + conn.send(message.encode()) except Exception as e: - self.log.error("Trapped Exception in Remote-Communication: %s", e) - - # In case of an Exception, return that - return False, str(e) - - def signal(self, origin_conn, command, args): - for conn in self.currentConnections: - if conn == origin_conn: - continue + self.log.warn(e) - self.log.debug( - 'signaling connection %s the successful ' - 'execution of the command %s', - conn.getpeername(), command) + return True - conn.makefile('w').write( - "signal %s %s\n" % (command, ' '.join(args)) - ) + def notify_all(self, msg): + try: + words = msg.split() + words[-1] = self.commands.encodeSourceName(int(words[-1])) + msg = " ".join(words) + '\n' + for queue in self.currentConnections.values(): + queue.put(msg) + except Exception as e: + self.log.debug("Error during notify: %s", e) |