PageRenderTime 22ms CodeModel.GetById 45ms RepoModel.GetById 0ms app.codeStats 0ms

/libqtile/ipc.py

https://github.com/dequis/qtile
Python | 249 lines | 170 code | 26 blank | 53 comment | 11 complexity | 6de5d6c537576cf08f2409a1fc7c25dd MD5 | raw file
  1. # Copyright (c) 2008, Aldo Cortesi. All rights reserved.
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. """
  21. A simple IPC mechanism for communicating between two local processes. We
  22. use marshal to serialize data - this means that both client and server must
  23. run the same Python version, and that clients must be trusted (as
  24. un-marshalling untrusted data can result in arbitrary code execution).
  25. """
  26. import marshal
  27. import os.path
  28. import socket
  29. import struct
  30. import fcntl
  31. import json
  32. from . import asyncio
  33. from .log_utils import logger
  34. HDRLEN = 4
  35. class IPCError(Exception):
  36. pass
  37. class _IPC(object):
  38. def _unpack(self, data):
  39. if data is None:
  40. raise IPCError("received data is None")
  41. try:
  42. return json.loads(data.decode('utf-8')), True
  43. except ValueError:
  44. pass
  45. try:
  46. assert len(data) >= HDRLEN
  47. size = struct.unpack("!L", data[:HDRLEN])[0]
  48. assert size >= len(data[HDRLEN:])
  49. return self._unpack_body(data[HDRLEN:HDRLEN + size]), False
  50. except AssertionError:
  51. raise IPCError(
  52. "error reading reply!"
  53. " (probably the socket was disconnected)"
  54. )
  55. @staticmethod
  56. def _unpack_body(body):
  57. return marshal.loads(body)
  58. @staticmethod
  59. def _pack_json(msg):
  60. json_obj = json.dumps(msg)
  61. return json_obj.encode('utf-8')
  62. @staticmethod
  63. def _pack(msg):
  64. msg = marshal.dumps(msg)
  65. size = struct.pack("!L", len(msg))
  66. return size + msg
  67. class _ClientProtocol(asyncio.Protocol, _IPC):
  68. """IPC Client Protocol
  69. 1. Once the connection is made, the client initializes a Future self.reply,
  70. which will hold the response from the server.
  71. 2. The message is sent to the server with .send(msg), which closes the
  72. connection once the message is sent.
  73. 3. The client then receives data from the server until the server closes
  74. the connection, signalling that all the data has been sent.
  75. 4. When the server sends on EOF, the data is unpacked and stored to the
  76. reply future.
  77. """
  78. def connection_made(self, transport):
  79. self.transport = transport
  80. self.recv = b''
  81. self.reply = asyncio.Future()
  82. def send(self, msg, is_json=False):
  83. if is_json:
  84. send_data = self._pack_json(msg)
  85. else:
  86. send_data = self._pack(msg)
  87. self.transport.write(send_data)
  88. try:
  89. self.transport.write_eof()
  90. except AttributeError:
  91. logger.exception('Swallowing AttributeError due to asyncio bug!')
  92. def data_received(self, data):
  93. self.recv += data
  94. def eof_received(self):
  95. # The server sends EOF when there is data ready to be processed
  96. try:
  97. data, _ = self._unpack(self.recv)
  98. except IPCError as e:
  99. self.reply.set_exception(e)
  100. else:
  101. self.reply.set_result(data)
  102. def connection_lost(self, exc):
  103. # The client shouldn't just lose the connection without an EOF
  104. if exc:
  105. self.reply.set_exception(exc)
  106. if not self.reply.done():
  107. self.reply.set_exception(IPCError)
  108. class Client(object):
  109. def __init__(self, fname, is_json=False):
  110. self.fname = fname
  111. self.loop = asyncio.get_event_loop()
  112. self.is_json = is_json
  113. def send(self, msg):
  114. client_coroutine = self.loop.create_unix_connection(_ClientProtocol, path=self.fname)
  115. try:
  116. _, client_proto = self.loop.run_until_complete(client_coroutine)
  117. except OSError:
  118. raise IPCError("Could not open %s" % self.fname)
  119. client_proto.send(msg, is_json=self.is_json)
  120. try:
  121. self.loop.run_until_complete(asyncio.wait_for(client_proto.reply, timeout=10))
  122. except asyncio.TimeoutError:
  123. raise RuntimeError("Server not responding")
  124. return client_proto.reply.result()
  125. def call(self, data):
  126. return self.send(data)
  127. class _ServerProtocol(asyncio.Protocol, _IPC):
  128. """IPC Server Protocol
  129. 1. The server is initialized with a handler callback function for evaluating
  130. incoming queries.
  131. 2. Once the connection is made, the server initializes a data store for
  132. incoming data.
  133. 3. The client sends all its data to the server, which is stored.
  134. 4. The client signals that all data is sent by sending an EOF, at which
  135. point the server then unpacks the data and runs it through the handler.
  136. The result is returned to the client and the connection is closed.
  137. """
  138. def __init__(self, handler):
  139. asyncio.Protocol.__init__(self)
  140. self.handler = handler
  141. self.transport = None
  142. self.data = None
  143. def connection_made(self, transport):
  144. self.transport = transport
  145. logger.info('Connection made to server')
  146. self.data = b''
  147. def data_received(self, recv):
  148. logger.info('Data received by server')
  149. self.data += recv
  150. def eof_received(self):
  151. logger.info('EOF received by server')
  152. try:
  153. req, is_json = self._unpack(self.data)
  154. except IPCError:
  155. logger.warn('Invalid data received, closing connection')
  156. self.transport.close()
  157. return
  158. finally:
  159. self.data = None
  160. if req[1] == 'restart':
  161. logger.info('Closing connection on restart')
  162. self.transport.write_eof()
  163. rep = self.handler(req)
  164. if is_json:
  165. result = self._pack_json(rep)
  166. else:
  167. result = self._pack(rep)
  168. logger.info('Sending result on receive EOF')
  169. self.transport.write(result)
  170. logger.info('Closing connection on receive EOF')
  171. self.transport.write_eof()
  172. class Server(object):
  173. def __init__(self, fname, handler, loop):
  174. self.fname = fname
  175. self.handler = handler
  176. self.loop = loop
  177. self.server = None
  178. if os.path.exists(fname):
  179. os.unlink(fname)
  180. self.sock = socket.socket(
  181. socket.AF_UNIX,
  182. socket.SOCK_STREAM,
  183. 0
  184. )
  185. flags = fcntl.fcntl(self.sock, fcntl.F_GETFD)
  186. fcntl.fcntl(self.sock, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
  187. self.sock.bind(self.fname)
  188. def close(self):
  189. logger.info('Stopping server on server close')
  190. self.server.close()
  191. self.sock.close()
  192. def start(self):
  193. serverprotocol = _ServerProtocol(self.handler)
  194. server_coroutine = self.loop.create_unix_server(lambda: serverprotocol, sock=self.sock, backlog=5)
  195. logger.info('Starting server')
  196. self.server = self.loop.run_until_complete(server_coroutine)