PageRenderTime 45ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/likeProjects_examples/qtile-0.10.1/libqtile/ipc.py

https://bitbucket.org/hackersgame/lavinder-prototype
Python | 221 lines | 145 code | 23 blank | 53 comment | 8 complexity | b2c561516a76b2e721058159545000cd MD5 | raw file
Possible License(s): GPL-2.0
  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 logging
  28. import os.path
  29. import socket
  30. import struct
  31. import fcntl
  32. from six.moves import asyncio
  33. HDRLEN = 4
  34. class IPCError(Exception):
  35. pass
  36. class _IPC(object):
  37. def _unpack(self, data):
  38. try:
  39. assert len(data) >= HDRLEN
  40. size = struct.unpack("!L", data[:HDRLEN])[0]
  41. assert size >= len(data[HDRLEN:])
  42. return self._unpack_body(data[HDRLEN:HDRLEN + size])
  43. except AssertionError:
  44. raise IPCError(
  45. "error reading reply!"
  46. " (probably the socket was disconnected)"
  47. )
  48. def _unpack_body(self, body):
  49. return marshal.loads(body)
  50. def _pack(self, msg):
  51. msg = marshal.dumps(msg)
  52. size = struct.pack("!L", len(msg))
  53. return size + msg
  54. class _ClientProtocol(asyncio.Protocol, _IPC):
  55. """IPC Client Protocol
  56. 1. Once the connection is made, the client initializes a Future self.reply,
  57. which will hold the response from the server.
  58. 2. The message is sent to the server with .send(msg), which closes the
  59. connection once the message is sent.
  60. 3. The client then recieves data from the server until the server closes
  61. the connection, signalling that all the data has been sent.
  62. 4. When the server sends on EOF, the data is unpacked and stored to the
  63. reply future.
  64. """
  65. def connection_made(self, transport):
  66. self.transport = transport
  67. self.recv = b''
  68. self.reply = asyncio.Future()
  69. def send(self, msg):
  70. self.transport.write(self._pack(msg))
  71. try:
  72. self.transport.write_eof()
  73. except AttributeError:
  74. log = logging.getLogger('qtile')
  75. log.exception('Swallowing AttributeError due to asyncio bug!')
  76. def data_received(self, data):
  77. self.recv += data
  78. def eof_received(self):
  79. # The server sends EOF when there is data ready to be processed
  80. try:
  81. data = self._unpack(self.recv)
  82. except IPCError as e:
  83. self.reply.set_exception(e)
  84. else:
  85. self.reply.set_result(data)
  86. def connection_lost(self, exc):
  87. # The client shouldn't just lose the connection without an EOF
  88. if exc:
  89. self.reply.set_exception(exc)
  90. if not self.reply.done():
  91. self.reply.set_exception(IPCError)
  92. class Client(object):
  93. def __init__(self, fname):
  94. self.fname = fname
  95. self.loop = asyncio.get_event_loop()
  96. def send(self, msg):
  97. client_coroutine = self.loop.create_unix_connection(_ClientProtocol, path=self.fname)
  98. try:
  99. _, client_proto = self.loop.run_until_complete(client_coroutine)
  100. except OSError:
  101. raise IPCError("Could not open %s" % self.fname)
  102. client_proto.send(msg)
  103. try:
  104. self.loop.run_until_complete(asyncio.wait_for(client_proto.reply, timeout=10))
  105. except asyncio.TimeoutError:
  106. raise RuntimeError("Server not responding")
  107. return client_proto.reply.result()
  108. def call(self, data):
  109. return self.send(data)
  110. class _ServerProtocol(asyncio.Protocol, _IPC):
  111. """IPC Server Protocol
  112. 1. The server is initalized with a handler callback function for evaluating
  113. incoming queries and a log.
  114. 2. Once the connection is made, the server initializes a data store for
  115. incoming data.
  116. 3. The client sends all its data to the server, which is stored.
  117. 4. The client signals that all data is sent by sending an EOF, at which
  118. point the server then unpacks the data and runs it through the handler.
  119. The result is returned to the client and the connection is closed.
  120. """
  121. def __init__(self, handler, log):
  122. asyncio.Protocol.__init__(self)
  123. self.handler = handler
  124. self.log = log
  125. def connection_made(self, transport):
  126. self.transport = transport
  127. self.log.info('Connection made to server')
  128. self.data = b''
  129. def data_received(self, recv):
  130. self.log.info('Data recieved by server')
  131. self.data += recv
  132. def eof_received(self):
  133. self.log.info('EOF recieved by server')
  134. try:
  135. req = self._unpack(self.data)
  136. except IPCError:
  137. self.log.info('Invalid data received, closing connection')
  138. self.transport.close()
  139. return
  140. finally:
  141. self.data = None
  142. if req[1] == 'restart':
  143. self.log.info('Closing connection on restart')
  144. self.transport.write_eof()
  145. rep = self.handler(req)
  146. result = self._pack(rep)
  147. self.log.info('Sending result on receive EOF')
  148. self.transport.write(result)
  149. self.log.info('Closing connection on receive EOF')
  150. self.transport.write_eof()
  151. class Server(object):
  152. def __init__(self, fname, handler):
  153. self.log = logging.getLogger('qtile')
  154. self.fname = fname
  155. self.handler = handler
  156. self.loop = asyncio.get_event_loop()
  157. if os.path.exists(fname):
  158. os.unlink(fname)
  159. self.sock = socket.socket(
  160. socket.AF_UNIX,
  161. socket.SOCK_STREAM,
  162. 0
  163. )
  164. flags = fcntl.fcntl(self.sock, fcntl.F_GETFD)
  165. fcntl.fcntl(self.sock, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
  166. self.sock.bind(self.fname)
  167. def close(self):
  168. self.log.info('Stopping server on server close')
  169. self.server.close()
  170. self.sock.close()
  171. def start(self):
  172. serverprotocol = _ServerProtocol(self.handler, self.log)
  173. server_coroutine = self.loop.create_unix_server(lambda: serverprotocol, sock=self.sock, backlog=5)
  174. self.log.info('Starting server')
  175. self.server = self.loop.run_until_complete(server_coroutine)