aboutsummaryrefslogtreecommitdiff
path: root/voctocore/lib/controlserver.py
blob: 87a28c8d934e5aada7a766af10440ada9007445b (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. self.log.debug('re-starting on_loop scheduling')
  48. GObject.idle_add(self.on_loop)
  49. self.command_queue.put((line, conn))
  50. if close_after:
  51. self.close_connection(conn)
  52. return False
  53. if lines[-1] != '':
  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. self.log.debug('on_loop called')
  61. if self.command_queue.empty():
  62. self.log.debug('command_queue is empty again, stopping on_loop scheduling')
  63. return False
  64. line, requestor = self.command_queue.get()
  65. words = line.split()
  66. if len(words) < 1:
  67. self.log.debug('command_queue is empty again, stopping on_loop scheduling')
  68. return True
  69. command = words[0]
  70. args = words[1:]
  71. self.log.info("processing command %r with args %s", command, args)
  72. response = None
  73. try:
  74. # deny calling private methods
  75. if command[0] == '_':
  76. self.log.info('private methods are not callable')
  77. raise KeyError()
  78. command_function = self.commands.__class__.__dict__[command]
  79. except KeyError as e:
  80. self.log.info("received unknown command %s", command)
  81. response = "error unknown command %s\n" % command
  82. else:
  83. try:
  84. responseObject = command_function(self.commands, *args)
  85. except Exception as e:
  86. message = str(e) or "<no message>"
  87. response = "error %s\n" % message
  88. else:
  89. if isinstance(responseObject, NotifyResponse):
  90. responseObject = [ responseObject ]
  91. if isinstance(responseObject, list):
  92. for obj in responseObject:
  93. signal = "%s\n" % str(obj)
  94. for conn in self.currentConnections:
  95. self._schedule_write(conn, signal)
  96. else:
  97. response = "%s\n" % str(responseObject)
  98. finally:
  99. if response is not None and requestor in self.currentConnections:
  100. self._schedule_write(requestor, response)
  101. return False
  102. def _schedule_write(self, conn, message):
  103. queue = self.currentConnections[conn]
  104. self.log.debug('re-starting on_write[%u] scheduling', conn.fileno())
  105. GObject.io_add_watch(conn, GObject.IO_OUT, self.on_write)
  106. queue.put(message)
  107. def on_write(self, conn, *args):
  108. self.log.debug('on_write[%u] called', conn.fileno())
  109. try:
  110. queue = self.currentConnections[conn]
  111. except KeyError:
  112. return False
  113. if queue.empty():
  114. self.log.debug('write_queue[%u] is empty again, stopping on_write scheduling', conn.fileno())
  115. return False
  116. message = queue.get()
  117. try:
  118. conn.send(message.encode())
  119. except Exception as e:
  120. self.log.warn(e)
  121. return True
  122. def notify_all(self, msg):
  123. try:
  124. words = msg.split()
  125. words[-1] = self.commands.encodeSourceName(int(words[-1]))
  126. msg = " ".join(words) + '\n'
  127. for conn in self.currentConnections:
  128. self._schedule_write(conn, msg)
  129. except Exception as e:
  130. self.log.debug("error during notify: %s", e)