logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

transports.py (10486B)


  1. """Abstract Transport class."""
  2. __all__ = (
  3. 'BaseTransport', 'ReadTransport', 'WriteTransport',
  4. 'Transport', 'DatagramTransport', 'SubprocessTransport',
  5. )
  6. class BaseTransport:
  7. """Base class for transports."""
  8. __slots__ = ('_extra',)
  9. def __init__(self, extra=None):
  10. if extra is None:
  11. extra = {}
  12. self._extra = extra
  13. def get_extra_info(self, name, default=None):
  14. """Get optional transport information."""
  15. return self._extra.get(name, default)
  16. def is_closing(self):
  17. """Return True if the transport is closing or closed."""
  18. raise NotImplementedError
  19. def close(self):
  20. """Close the transport.
  21. Buffered data will be flushed asynchronously. No more data
  22. will be received. After all buffered data is flushed, the
  23. protocol's connection_lost() method will (eventually) be
  24. called with None as its argument.
  25. """
  26. raise NotImplementedError
  27. def set_protocol(self, protocol):
  28. """Set a new protocol."""
  29. raise NotImplementedError
  30. def get_protocol(self):
  31. """Return the current protocol."""
  32. raise NotImplementedError
  33. class ReadTransport(BaseTransport):
  34. """Interface for read-only transports."""
  35. __slots__ = ()
  36. def is_reading(self):
  37. """Return True if the transport is receiving."""
  38. raise NotImplementedError
  39. def pause_reading(self):
  40. """Pause the receiving end.
  41. No data will be passed to the protocol's data_received()
  42. method until resume_reading() is called.
  43. """
  44. raise NotImplementedError
  45. def resume_reading(self):
  46. """Resume the receiving end.
  47. Data received will once again be passed to the protocol's
  48. data_received() method.
  49. """
  50. raise NotImplementedError
  51. class WriteTransport(BaseTransport):
  52. """Interface for write-only transports."""
  53. __slots__ = ()
  54. def set_write_buffer_limits(self, high=None, low=None):
  55. """Set the high- and low-water limits for write flow control.
  56. These two values control when to call the protocol's
  57. pause_writing() and resume_writing() methods. If specified,
  58. the low-water limit must be less than or equal to the
  59. high-water limit. Neither value can be negative.
  60. The defaults are implementation-specific. If only the
  61. high-water limit is given, the low-water limit defaults to an
  62. implementation-specific value less than or equal to the
  63. high-water limit. Setting high to zero forces low to zero as
  64. well, and causes pause_writing() to be called whenever the
  65. buffer becomes non-empty. Setting low to zero causes
  66. resume_writing() to be called only once the buffer is empty.
  67. Use of zero for either limit is generally sub-optimal as it
  68. reduces opportunities for doing I/O and computation
  69. concurrently.
  70. """
  71. raise NotImplementedError
  72. def get_write_buffer_size(self):
  73. """Return the current size of the write buffer."""
  74. raise NotImplementedError
  75. def write(self, data):
  76. """Write some data bytes to the transport.
  77. This does not block; it buffers the data and arranges for it
  78. to be sent out asynchronously.
  79. """
  80. raise NotImplementedError
  81. def writelines(self, list_of_data):
  82. """Write a list (or any iterable) of data bytes to the transport.
  83. The default implementation concatenates the arguments and
  84. calls write() on the result.
  85. """
  86. data = b''.join(list_of_data)
  87. self.write(data)
  88. def write_eof(self):
  89. """Close the write end after flushing buffered data.
  90. (This is like typing ^D into a UNIX program reading from stdin.)
  91. Data may still be received.
  92. """
  93. raise NotImplementedError
  94. def can_write_eof(self):
  95. """Return True if this transport supports write_eof(), False if not."""
  96. raise NotImplementedError
  97. def abort(self):
  98. """Close the transport immediately.
  99. Buffered data will be lost. No more data will be received.
  100. The protocol's connection_lost() method will (eventually) be
  101. called with None as its argument.
  102. """
  103. raise NotImplementedError
  104. class Transport(ReadTransport, WriteTransport):
  105. """Interface representing a bidirectional transport.
  106. There may be several implementations, but typically, the user does
  107. not implement new transports; rather, the platform provides some
  108. useful transports that are implemented using the platform's best
  109. practices.
  110. The user never instantiates a transport directly; they call a
  111. utility function, passing it a protocol factory and other
  112. information necessary to create the transport and protocol. (E.g.
  113. EventLoop.create_connection() or EventLoop.create_server().)
  114. The utility function will asynchronously create a transport and a
  115. protocol and hook them up by calling the protocol's
  116. connection_made() method, passing it the transport.
  117. The implementation here raises NotImplemented for every method
  118. except writelines(), which calls write() in a loop.
  119. """
  120. __slots__ = ()
  121. class DatagramTransport(BaseTransport):
  122. """Interface for datagram (UDP) transports."""
  123. __slots__ = ()
  124. def sendto(self, data, addr=None):
  125. """Send data to the transport.
  126. This does not block; it buffers the data and arranges for it
  127. to be sent out asynchronously.
  128. addr is target socket address.
  129. If addr is None use target address pointed on transport creation.
  130. """
  131. raise NotImplementedError
  132. def abort(self):
  133. """Close the transport immediately.
  134. Buffered data will be lost. No more data will be received.
  135. The protocol's connection_lost() method will (eventually) be
  136. called with None as its argument.
  137. """
  138. raise NotImplementedError
  139. class SubprocessTransport(BaseTransport):
  140. __slots__ = ()
  141. def get_pid(self):
  142. """Get subprocess id."""
  143. raise NotImplementedError
  144. def get_returncode(self):
  145. """Get subprocess returncode.
  146. See also
  147. http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode
  148. """
  149. raise NotImplementedError
  150. def get_pipe_transport(self, fd):
  151. """Get transport for pipe with number fd."""
  152. raise NotImplementedError
  153. def send_signal(self, signal):
  154. """Send signal to subprocess.
  155. See also:
  156. docs.python.org/3/library/subprocess#subprocess.Popen.send_signal
  157. """
  158. raise NotImplementedError
  159. def terminate(self):
  160. """Stop the subprocess.
  161. Alias for close() method.
  162. On Posix OSs the method sends SIGTERM to the subprocess.
  163. On Windows the Win32 API function TerminateProcess()
  164. is called to stop the subprocess.
  165. See also:
  166. http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate
  167. """
  168. raise NotImplementedError
  169. def kill(self):
  170. """Kill the subprocess.
  171. On Posix OSs the function sends SIGKILL to the subprocess.
  172. On Windows kill() is an alias for terminate().
  173. See also:
  174. http://docs.python.org/3/library/subprocess#subprocess.Popen.kill
  175. """
  176. raise NotImplementedError
  177. class _FlowControlMixin(Transport):
  178. """All the logic for (write) flow control in a mix-in base class.
  179. The subclass must implement get_write_buffer_size(). It must call
  180. _maybe_pause_protocol() whenever the write buffer size increases,
  181. and _maybe_resume_protocol() whenever it decreases. It may also
  182. override set_write_buffer_limits() (e.g. to specify different
  183. defaults).
  184. The subclass constructor must call super().__init__(extra). This
  185. will call set_write_buffer_limits().
  186. The user may call set_write_buffer_limits() and
  187. get_write_buffer_size(), and their protocol's pause_writing() and
  188. resume_writing() may be called.
  189. """
  190. __slots__ = ('_loop', '_protocol_paused', '_high_water', '_low_water')
  191. def __init__(self, extra=None, loop=None):
  192. super().__init__(extra)
  193. assert loop is not None
  194. self._loop = loop
  195. self._protocol_paused = False
  196. self._set_write_buffer_limits()
  197. def _maybe_pause_protocol(self):
  198. size = self.get_write_buffer_size()
  199. if size <= self._high_water:
  200. return
  201. if not self._protocol_paused:
  202. self._protocol_paused = True
  203. try:
  204. self._protocol.pause_writing()
  205. except (SystemExit, KeyboardInterrupt):
  206. raise
  207. except BaseException as exc:
  208. self._loop.call_exception_handler({
  209. 'message': 'protocol.pause_writing() failed',
  210. 'exception': exc,
  211. 'transport': self,
  212. 'protocol': self._protocol,
  213. })
  214. def _maybe_resume_protocol(self):
  215. if (self._protocol_paused and
  216. self.get_write_buffer_size() <= self._low_water):
  217. self._protocol_paused = False
  218. try:
  219. self._protocol.resume_writing()
  220. except (SystemExit, KeyboardInterrupt):
  221. raise
  222. except BaseException as exc:
  223. self._loop.call_exception_handler({
  224. 'message': 'protocol.resume_writing() failed',
  225. 'exception': exc,
  226. 'transport': self,
  227. 'protocol': self._protocol,
  228. })
  229. def get_write_buffer_limits(self):
  230. return (self._low_water, self._high_water)
  231. def _set_write_buffer_limits(self, high=None, low=None):
  232. if high is None:
  233. if low is None:
  234. high = 64 * 1024
  235. else:
  236. high = 4 * low
  237. if low is None:
  238. low = high // 4
  239. if not high >= low >= 0:
  240. raise ValueError(
  241. f'high ({high!r}) must be >= low ({low!r}) must be >= 0')
  242. self._high_water = high
  243. self._low_water = low
  244. def set_write_buffer_limits(self, high=None, low=None):
  245. self._set_write_buffer_limits(high=high, low=low)
  246. self._maybe_pause_protocol()
  247. def get_write_buffer_size(self):
  248. raise NotImplementedError