- #!/usr/bin/python3
- import socket, logging, traceback
- from queue import Queue
- from gi.repository import GObject
- from lib.commands import ControlServerCommands
- from lib.tcpmulticonnection import TCPMultiConnection
- from lib.response import NotifyResponse, OkResponse
- class ControlServer(TCPMultiConnection):
- def __init__(self, pipeline):
- '''Initialize server and start listening.'''
- 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, [''])
- GObject.io_add_watch(conn, GObject.IO_OUT, self.on_write)
- def on_data(self, conn, _, leftovers, *args):
- '''Asynchronous connection handler. Pushes data from socket
- into command queue linewise'''
- close_after = False
- try:
- while True:
- try:
- leftovers.append(conn.recv(4096).decode(errors='replace'))
- if len(leftovers[-1]) == 0:
- self.log.info("Socket was closed")
- leftovers.pop()
- close_after = True
- break
- 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))
- if close_after:
- self.close_connection(conn)
- return False
- self.log.debug("Remaining %r", lines[-1])
- leftovers.append(lines[-1])
- return True
- 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()
- words = line.split()
|