transports.py 9.7 KB

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