summaryrefslogtreecommitdiff
path: root/voctocore/lib/controlserver.py
blob: 631770b9a943609f4c5b05a1b1b0254b75949e76 (plain)
  1. #!/usr/bin/python3
  2. import socket, logging, traceback
  3. from queue import Queue
  4. from gi.repository import GObject
  5. from lib.commands import ControlServerCommands
  6. from lib.tcpmulticonnection import TCPMultiConnection
  7. from lib.response import NotifyResponse, OkResponse
  8. class ControlServer(TCPMultiConnection):
  9. def __init__(self, pipeline):
  10. '''Initialize server and start listening.'''
  11. self.log = logging.getLogger('ControlServer')
  12. super().__init__(port=9999)
  13. self.command_queue = Queue()
  14. self.commands = ControlServerCommands(pipeline)
  15. GObject.idle_add(self.on_loop)
  16. def on_accepted(self, conn, addr):
  17. '''Asynchronous connection listener. Starts a handler for each connection.'''
  18. self.log.debug('Setting GObject io-watch on Connection')
  19. GObject.io_add_watch(conn, GObject.IO_IN, self.on_data, [''])
  20. GObject.io_add_watch(conn, GObject.IO_OUT, self.on_write)
  21. def on_data(self, conn, _, leftovers, *args):
  22. '''Asynchronous connection handler. Pushes data from socket
  23. into command queue linewise'''
  24. close_after = False
  25. try:
  26. while True:
  27. try:
  28. leftovers.append(conn.recv(4096).decode(errors='replace'))
  29. if len(leftovers[-1]) == 0:
  30. self.log.info("Socket was closed")
  31. leftovers.pop()
  32. close_after = True
  33. break
  34. except UnicodeDecodeError as e:
  35. continue
  36. except BlockingIOError as e:
  37. pass
  38. data = "".join(leftovers)
  39. leftovers.clear()
  40. lines = data.split('\n')
  41. for line in lines[:-1]:
  42. self.log.debug("Got line: %r", line)
  43. line = line.strip()
  44. # TODO: move quit to on_loop
  45. # 'quit' = remote wants us to close the connection
  46. if line == 'quit':
  47. self.log.info("Client asked us to close the Connection")
  48. self.close_connection(conn)
  49. return False
  50. self.command_queue.put((line, conn))
  51. if close_after:
  52. self.close_connection(conn)
  53. return False
  54. self.log.debug("Remaining %r", lines[-1])
  55. leftovers.append(lines[-1])
  56. return True
  57. def on_loop(self):
  58. '''Command handler. Processes commands in the command queue whenever
  59. nothing else is happening (registered as GObject idle callback)'''
  60. if self.command_queue.empty():
  61. return True
  62. line, requestor = self.command_queue.get()
  63. words = line.split()
  64. if len(words) < 1:
  65. return True
  66. command = words[0]
  67. args = words[1:]
  68. try:
  69. command_function = self.commands.__class__.__dict__[command]
  70. except KeyError as e:
  71. response = "error unknown command %s\n" % command
  72. else:
  73. try:
  74. responseObject = command_function(self.commands, *args)
  75. except Exception as e:
  76. message = str(e) or "<no message>"
  77. response = "error %s\n" % message
  78. else:
  79. if isinstance(responseObject, NotifyResponse):
  80. signal = "%s\n" % str(responseObject)
  81. for conn, queue in self.currentConnections.items():
  82. if conn == requestor:
  83. continue
  84. queue.put(signal)
  85. response = "%s\n" % str(responseObject)
  86. finally:
  87. if requestor in self.currentConnections:
  88. self.currentConnections[requestor].put(response)
  89. return True
  90. def on_write(self, conn, *args):
  91. # TODO: on_loop() is not called as soon as there is a writable socket
  92. self.on_loop()
  93. try:
  94. queue = self.currentConnections[conn]
  95. except KeyError:
  96. return False
  97. if queue.empty():
  98. return True
  99. message = queue.get()
  100. try:
  101. conn.send(message.encode())
  102. except Exception as e:
  103. self.log.warn(e)
  104. return True
  105. def notify_all(self, msg):
  106. try:
  107. words = msg.split()
  108. words[-1] = self.commands.encodeSourceName(int(words[-1]))
  109. msg = " ".join(words) + '\n'
  110. for queue in self.currentConnections.values():
  111. queue.put(msg)
  112. except Exception as e:
  113. self.log.debug("Error during notify: %s", e)