io.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. # dockerpty: io.py
  2. #
  3. # Copyright 2014 Chris Corbyn <[email protected]>
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import os
  17. import fcntl
  18. import errno
  19. import struct
  20. import select as builtin_select
  21. def set_blocking(fd, blocking=True):
  22. """
  23. Set the given file-descriptor blocking or non-blocking.
  24. Returns the original blocking status.
  25. """
  26. old_flag = fcntl.fcntl(fd, fcntl.F_GETFL)
  27. if blocking:
  28. new_flag = old_flag &~ os.O_NONBLOCK
  29. else:
  30. new_flag = old_flag | os.O_NONBLOCK
  31. fcntl.fcntl(fd, fcntl.F_SETFL, new_flag)
  32. return not bool(old_flag & os.O_NONBLOCK)
  33. def select(read_streams, timeout=0):
  34. """
  35. Select the streams from `read_streams` that are ready for reading.
  36. Uses `select.select()` internally but returns a flat list of streams.
  37. """
  38. write_streams = []
  39. exception_streams = []
  40. try:
  41. return builtin_select.select(
  42. read_streams,
  43. write_streams,
  44. exception_streams,
  45. timeout,
  46. )[0]
  47. except builtin_select.error as e:
  48. # POSIX signals interrupt select()
  49. if e[0] == errno.EINTR:
  50. return []
  51. else:
  52. raise e
  53. class Stream(object):
  54. """
  55. Generic Stream class.
  56. This is a file-like abstraction on top of os.read() and os.write(), which
  57. add consistency to the reading of sockets and files alike.
  58. """
  59. """
  60. Recoverable IO/OS Errors.
  61. """
  62. ERRNO_RECOVERABLE = [
  63. errno.EINTR,
  64. errno.EDEADLK,
  65. errno.EWOULDBLOCK,
  66. ]
  67. def __init__(self, fd):
  68. """
  69. Initialize the Stream for the file descriptor `fd`.
  70. The `fd` object must have a `fileno()` method.
  71. """
  72. self.fd = fd
  73. def fileno(self):
  74. """
  75. Return the fileno() of the file descriptor.
  76. """
  77. return self.fd.fileno()
  78. def set_blocking(self, value):
  79. if hasattr(self.fd, 'setblocking'):
  80. self.fd.setblocking(value)
  81. return True
  82. else:
  83. return set_blocking(self.fd, value)
  84. def read(self, n=4096):
  85. """
  86. Return `n` bytes of data from the Stream, or None at end of stream.
  87. """
  88. try:
  89. if hasattr(self.fd, 'recv'):
  90. return self.fd.recv(n)
  91. return os.read(self.fd.fileno(), n)
  92. except EnvironmentError as e:
  93. if e.errno not in Stream.ERRNO_RECOVERABLE:
  94. raise e
  95. def write(self, data):
  96. """
  97. Write `data` to the Stream.
  98. """
  99. if not data:
  100. return None
  101. while True:
  102. try:
  103. if hasattr(self.fd, 'send'):
  104. self.fd.send(data)
  105. return len(data)
  106. os.write(self.fd.fileno(), data)
  107. return len(data)
  108. except EnvironmentError as e:
  109. if e.errno not in Stream.ERRNO_RECOVERABLE:
  110. raise e
  111. def __repr__(self):
  112. return "{cls}({fd})".format(cls=type(self).__name__, fd=self.fd)
  113. class Demuxer(object):
  114. """
  115. Wraps a multiplexed Stream to read in data demultiplexed.
  116. Docker multiplexes streams together when there is no PTY attached, by
  117. sending an 8-byte header, followed by a chunk of data.
  118. The first 4 bytes of the header denote the stream from which the data came
  119. (i.e. 0x01 = stdout, 0x02 = stderr). Only the first byte of these initial 4
  120. bytes is used.
  121. The next 4 bytes indicate the length of the following chunk of data as an
  122. integer in big endian format. This much data must be consumed before the
  123. next 8-byte header is read.
  124. """
  125. def __init__(self, stream):
  126. """
  127. Initialize a new Demuxer reading from `stream`.
  128. """
  129. self.stream = stream
  130. self.remain = 0
  131. def fileno(self):
  132. """
  133. Returns the fileno() of the underlying Stream.
  134. This is useful for select() to work.
  135. """
  136. return self.stream.fileno()
  137. def set_blocking(self, value):
  138. return self.stream.set_blocking(value)
  139. def read(self, n=4096):
  140. """
  141. Read up to `n` bytes of data from the Stream, after demuxing.
  142. Less than `n` bytes of data may be returned depending on the available
  143. payload, but the number of bytes returned will never exceed `n`.
  144. Because demuxing involves scanning 8-byte headers, the actual amount of
  145. data read from the underlying stream may be greater than `n`.
  146. """
  147. size = self._next_packet_size(n)
  148. if size <= 0:
  149. return
  150. else:
  151. return self.stream.read(size)
  152. def write(self, data):
  153. """
  154. Delegates the the underlying Stream.
  155. """
  156. return self.stream.write(data)
  157. def _next_packet_size(self, n=0):
  158. size = 0
  159. if self.remain > 0:
  160. size = min(n, self.remain)
  161. self.remain -= size
  162. else:
  163. data = self.stream.read(8)
  164. if data is None:
  165. return 0
  166. if len(data) == 8:
  167. __, actual = struct.unpack('>BxxxL', data)
  168. size = min(n, actual)
  169. self.remain = actual - size
  170. return size
  171. def __repr__(self):
  172. return "{cls}({stream})".format(cls=type(self).__name__,
  173. stream=self.stream)
  174. class Pump(object):
  175. """
  176. Stream pump class.
  177. A Pump wraps two Streams, reading from one and and writing its data into
  178. the other, much like a pipe but manually managed.
  179. This abstraction is used to facilitate piping data between the file
  180. descriptors associated with the tty and those associated with a container's
  181. allocated pty.
  182. Pumps are selectable based on the 'read' end of the pipe.
  183. """
  184. def __init__(self, from_stream, to_stream):
  185. """
  186. Initialize a Pump with a Stream to read from and another to write to.
  187. """
  188. self.from_stream = from_stream
  189. self.to_stream = to_stream
  190. def fileno(self):
  191. """
  192. Returns the `fileno()` of the reader end of the Pump.
  193. This is useful to allow Pumps to function with `select()`.
  194. """
  195. return self.from_stream.fileno()
  196. def set_blocking(self, value):
  197. return self.from_stream.set_blocking(value)
  198. def flush(self, n=4096):
  199. """
  200. Flush `n` bytes of data from the reader Stream to the writer Stream.
  201. Returns the number of bytes that were actually flushed. A return value
  202. of zero is not an error.
  203. If EOF has been reached, `None` is returned.
  204. """
  205. try:
  206. return self.to_stream.write(self.from_stream.read(n))
  207. except OSError as e:
  208. if e.errno != errno.EPIPE:
  209. raise e
  210. def __repr__(self):
  211. return "{cls}(from={from_stream}, to={to_stream})".format(
  212. cls=type(self).__name__,
  213. from_stream=self.from_stream,
  214. to_stream=self.to_stream)