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