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