lazy_wheel.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. """Lazy ZIP over HTTP"""
  2. __all__ = ['HTTPRangeRequestUnsupported', 'dist_from_wheel_url']
  3. from bisect import bisect_left, bisect_right
  4. from contextlib import contextmanager
  5. from tempfile import NamedTemporaryFile
  6. from zipfile import BadZipfile, ZipFile
  7. from pip._vendor.requests.models import CONTENT_CHUNK_SIZE
  8. from pip._vendor.six.moves import range
  9. from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks
  10. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  11. from pip._internal.utils.wheel import pkg_resources_distribution_for_wheel
  12. if MYPY_CHECK_RUNNING:
  13. from typing import Any, Dict, Iterator, List, Optional, Tuple
  14. from pip._vendor.pkg_resources import Distribution
  15. from pip._vendor.requests.models import Response
  16. from pip._internal.network.session import PipSession
  17. class HTTPRangeRequestUnsupported(Exception):
  18. pass
  19. def dist_from_wheel_url(name, url, session):
  20. # type: (str, str, PipSession) -> Distribution
  21. """Return a pkg_resources.Distribution from the given wheel URL.
  22. This uses HTTP range requests to only fetch the potion of the wheel
  23. containing metadata, just enough for the object to be constructed.
  24. If such requests are not supported, HTTPRangeRequestUnsupported
  25. is raised.
  26. """
  27. with LazyZipOverHTTP(url, session) as wheel:
  28. # For read-only ZIP files, ZipFile only needs methods read,
  29. # seek, seekable and tell, not the whole IO protocol.
  30. zip_file = ZipFile(wheel) # type: ignore
  31. # After context manager exit, wheel.name
  32. # is an invalid file by intention.
  33. return pkg_resources_distribution_for_wheel(zip_file, name, wheel.name)
  34. class LazyZipOverHTTP(object):
  35. """File-like object mapped to a ZIP file over HTTP.
  36. This uses HTTP range requests to lazily fetch the file's content,
  37. which is supposed to be fed to ZipFile. If such requests are not
  38. supported by the server, raise HTTPRangeRequestUnsupported
  39. during initialization.
  40. """
  41. def __init__(self, url, session, chunk_size=CONTENT_CHUNK_SIZE):
  42. # type: (str, PipSession, int) -> None
  43. head = session.head(url, headers=HEADERS)
  44. raise_for_status(head)
  45. assert head.status_code == 200
  46. self._session, self._url, self._chunk_size = session, url, chunk_size
  47. self._length = int(head.headers['Content-Length'])
  48. self._file = NamedTemporaryFile()
  49. self.truncate(self._length)
  50. self._left = [] # type: List[int]
  51. self._right = [] # type: List[int]
  52. if 'bytes' not in head.headers.get('Accept-Ranges', 'none'):
  53. raise HTTPRangeRequestUnsupported('range request is not supported')
  54. self._check_zip()
  55. @property
  56. def mode(self):
  57. # type: () -> str
  58. """Opening mode, which is always rb."""
  59. return 'rb'
  60. @property
  61. def name(self):
  62. # type: () -> str
  63. """Path to the underlying file."""
  64. return self._file.name
  65. def seekable(self):
  66. # type: () -> bool
  67. """Return whether random access is supported, which is True."""
  68. return True
  69. def close(self):
  70. # type: () -> None
  71. """Close the file."""
  72. self._file.close()
  73. @property
  74. def closed(self):
  75. # type: () -> bool
  76. """Whether the file is closed."""
  77. return self._file.closed
  78. def read(self, size=-1):
  79. # type: (int) -> bytes
  80. """Read up to size bytes from the object and return them.
  81. As a convenience, if size is unspecified or -1,
  82. all bytes until EOF are returned. Fewer than
  83. size bytes may be returned if EOF is reached.
  84. """
  85. download_size = max(size, self._chunk_size)
  86. start, length = self.tell(), self._length
  87. stop = length if size < 0 else min(start+download_size, length)
  88. start = max(0, stop-download_size)
  89. self._download(start, stop-1)
  90. return self._file.read(size)
  91. def readable(self):
  92. # type: () -> bool
  93. """Return whether the file is readable, which is True."""
  94. return True
  95. def seek(self, offset, whence=0):
  96. # type: (int, int) -> int
  97. """Change stream position and return the new absolute position.
  98. Seek to offset relative position indicated by whence:
  99. * 0: Start of stream (the default). pos should be >= 0;
  100. * 1: Current position - pos may be negative;
  101. * 2: End of stream - pos usually negative.
  102. """
  103. return self._file.seek(offset, whence)
  104. def tell(self):
  105. # type: () -> int
  106. """Return the current possition."""
  107. return self._file.tell()
  108. def truncate(self, size=None):
  109. # type: (Optional[int]) -> int
  110. """Resize the stream to the given size in bytes.
  111. If size is unspecified resize to the current position.
  112. The current stream position isn't changed.
  113. Return the new file size.
  114. """
  115. return self._file.truncate(size)
  116. def writable(self):
  117. # type: () -> bool
  118. """Return False."""
  119. return False
  120. def __enter__(self):
  121. # type: () -> LazyZipOverHTTP
  122. self._file.__enter__()
  123. return self
  124. def __exit__(self, *exc):
  125. # type: (*Any) -> Optional[bool]
  126. return self._file.__exit__(*exc)
  127. @contextmanager
  128. def _stay(self):
  129. # type: ()-> Iterator[None]
  130. """Return a context manager keeping the position.
  131. At the end of the block, seek back to original position.
  132. """
  133. pos = self.tell()
  134. try:
  135. yield
  136. finally:
  137. self.seek(pos)
  138. def _check_zip(self):
  139. # type: () -> None
  140. """Check and download until the file is a valid ZIP."""
  141. end = self._length - 1
  142. for start in reversed(range(0, end, self._chunk_size)):
  143. self._download(start, end)
  144. with self._stay():
  145. try:
  146. # For read-only ZIP files, ZipFile only needs
  147. # methods read, seek, seekable and tell.
  148. ZipFile(self) # type: ignore
  149. except BadZipfile:
  150. pass
  151. else:
  152. break
  153. def _stream_response(self, start, end, base_headers=HEADERS):
  154. # type: (int, int, Dict[str, str]) -> Response
  155. """Return HTTP response to a range request from start to end."""
  156. headers = base_headers.copy()
  157. headers['Range'] = 'bytes={}-{}'.format(start, end)
  158. # TODO: Get range requests to be correctly cached
  159. headers['Cache-Control'] = 'no-cache'
  160. return self._session.get(self._url, headers=headers, stream=True)
  161. def _merge(self, start, end, left, right):
  162. # type: (int, int, int, int) -> Iterator[Tuple[int, int]]
  163. """Return an iterator of intervals to be fetched.
  164. Args:
  165. start (int): Start of needed interval
  166. end (int): End of needed interval
  167. left (int): Index of first overlapping downloaded data
  168. right (int): Index after last overlapping downloaded data
  169. """
  170. lslice, rslice = self._left[left:right], self._right[left:right]
  171. i = start = min([start]+lslice[:1])
  172. end = max([end]+rslice[-1:])
  173. for j, k in zip(lslice, rslice):
  174. if j > i:
  175. yield i, j-1
  176. i = k + 1
  177. if i <= end:
  178. yield i, end
  179. self._left[left:right], self._right[left:right] = [start], [end]
  180. def _download(self, start, end):
  181. # type: (int, int) -> None
  182. """Download bytes from start to end inclusively."""
  183. with self._stay():
  184. left = bisect_left(self._right, start)
  185. right = bisect_right(self._left, end)
  186. for start, end in self._merge(start, end, left, right):
  187. response = self._stream_response(start, end)
  188. response.raise_for_status()
  189. self.seek(start)
  190. for chunk in response_chunks(response, self._chunk_size):
  191. self._file.write(chunk)