You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cache.py 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. """Cache Management
  2. """
  3. import errno
  4. import hashlib
  5. import logging
  6. import os
  7. from pip._vendor.packaging.utils import canonicalize_name
  8. from pip._internal.download import path_to_url
  9. from pip._internal.models.link import Link
  10. from pip._internal.utils.compat import expanduser
  11. from pip._internal.utils.temp_dir import TempDirectory
  12. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  13. from pip._internal.wheel import InvalidWheelFilename, Wheel
  14. if MYPY_CHECK_RUNNING:
  15. from typing import Optional, Set, List, Any # noqa: F401
  16. from pip._internal.index import FormatControl # noqa: F401
  17. logger = logging.getLogger(__name__)
  18. class Cache(object):
  19. """An abstract class - provides cache directories for data from links
  20. :param cache_dir: The root of the cache.
  21. :param format_control: An object of FormatControl class to limit
  22. binaries being read from the cache.
  23. :param allowed_formats: which formats of files the cache should store.
  24. ('binary' and 'source' are the only allowed values)
  25. """
  26. def __init__(self, cache_dir, format_control, allowed_formats):
  27. # type: (str, FormatControl, Set[str]) -> None
  28. super(Cache, self).__init__()
  29. self.cache_dir = expanduser(cache_dir) if cache_dir else None
  30. self.format_control = format_control
  31. self.allowed_formats = allowed_formats
  32. _valid_formats = {"source", "binary"}
  33. assert self.allowed_formats.union(_valid_formats) == _valid_formats
  34. def _get_cache_path_parts(self, link):
  35. # type: (Link) -> List[str]
  36. """Get parts of part that must be os.path.joined with cache_dir
  37. """
  38. # We want to generate an url to use as our cache key, we don't want to
  39. # just re-use the URL because it might have other items in the fragment
  40. # and we don't care about those.
  41. key_parts = [link.url_without_fragment]
  42. if link.hash_name is not None and link.hash is not None:
  43. key_parts.append("=".join([link.hash_name, link.hash]))
  44. key_url = "#".join(key_parts)
  45. # Encode our key url with sha224, we'll use this because it has similar
  46. # security properties to sha256, but with a shorter total output (and
  47. # thus less secure). However the differences don't make a lot of
  48. # difference for our use case here.
  49. hashed = hashlib.sha224(key_url.encode()).hexdigest()
  50. # We want to nest the directories some to prevent having a ton of top
  51. # level directories where we might run out of sub directories on some
  52. # FS.
  53. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
  54. return parts
  55. def _get_candidates(self, link, package_name):
  56. # type: (Link, Optional[str]) -> List[Any]
  57. can_not_cache = (
  58. not self.cache_dir or
  59. not package_name or
  60. not link
  61. )
  62. if can_not_cache:
  63. return []
  64. canonical_name = canonicalize_name(package_name)
  65. formats = self.format_control.get_allowed_formats(
  66. canonical_name
  67. )
  68. if not self.allowed_formats.intersection(formats):
  69. return []
  70. root = self.get_path_for_link(link)
  71. try:
  72. return os.listdir(root)
  73. except OSError as err:
  74. if err.errno in {errno.ENOENT, errno.ENOTDIR}:
  75. return []
  76. raise
  77. def get_path_for_link(self, link):
  78. # type: (Link) -> str
  79. """Return a directory to store cached items in for link.
  80. """
  81. raise NotImplementedError()
  82. def get(self, link, package_name):
  83. # type: (Link, Optional[str]) -> Link
  84. """Returns a link to a cached item if it exists, otherwise returns the
  85. passed link.
  86. """
  87. raise NotImplementedError()
  88. def _link_for_candidate(self, link, candidate):
  89. # type: (Link, str) -> Link
  90. root = self.get_path_for_link(link)
  91. path = os.path.join(root, candidate)
  92. return Link(path_to_url(path))
  93. def cleanup(self):
  94. # type: () -> None
  95. pass
  96. class SimpleWheelCache(Cache):
  97. """A cache of wheels for future installs.
  98. """
  99. def __init__(self, cache_dir, format_control):
  100. # type: (str, FormatControl) -> None
  101. super(SimpleWheelCache, self).__init__(
  102. cache_dir, format_control, {"binary"}
  103. )
  104. def get_path_for_link(self, link):
  105. # type: (Link) -> str
  106. """Return a directory to store cached wheels for link
  107. Because there are M wheels for any one sdist, we provide a directory
  108. to cache them in, and then consult that directory when looking up
  109. cache hits.
  110. We only insert things into the cache if they have plausible version
  111. numbers, so that we don't contaminate the cache with things that were
  112. not unique. E.g. ./package might have dozens of installs done for it
  113. and build a version of 0.0...and if we built and cached a wheel, we'd
  114. end up using the same wheel even if the source has been edited.
  115. :param link: The link of the sdist for which this will cache wheels.
  116. """
  117. parts = self._get_cache_path_parts(link)
  118. # Store wheels within the root cache_dir
  119. return os.path.join(self.cache_dir, "wheels", *parts)
  120. def get(self, link, package_name):
  121. # type: (Link, Optional[str]) -> Link
  122. candidates = []
  123. for wheel_name in self._get_candidates(link, package_name):
  124. try:
  125. wheel = Wheel(wheel_name)
  126. except InvalidWheelFilename:
  127. continue
  128. if not wheel.supported():
  129. # Built for a different python/arch/etc
  130. continue
  131. candidates.append((wheel.support_index_min(), wheel_name))
  132. if not candidates:
  133. return link
  134. return self._link_for_candidate(link, min(candidates)[1])
  135. class EphemWheelCache(SimpleWheelCache):
  136. """A SimpleWheelCache that creates it's own temporary cache directory
  137. """
  138. def __init__(self, format_control):
  139. # type: (FormatControl) -> None
  140. self._temp_dir = TempDirectory(kind="ephem-wheel-cache")
  141. self._temp_dir.create()
  142. super(EphemWheelCache, self).__init__(
  143. self._temp_dir.path, format_control
  144. )
  145. def cleanup(self):
  146. # type: () -> None
  147. self._temp_dir.cleanup()
  148. class WheelCache(Cache):
  149. """Wraps EphemWheelCache and SimpleWheelCache into a single Cache
  150. This Cache allows for gracefully degradation, using the ephem wheel cache
  151. when a certain link is not found in the simple wheel cache first.
  152. """
  153. def __init__(self, cache_dir, format_control):
  154. # type: (str, FormatControl) -> None
  155. super(WheelCache, self).__init__(
  156. cache_dir, format_control, {'binary'}
  157. )
  158. self._wheel_cache = SimpleWheelCache(cache_dir, format_control)
  159. self._ephem_cache = EphemWheelCache(format_control)
  160. def get_path_for_link(self, link):
  161. # type: (Link) -> str
  162. return self._wheel_cache.get_path_for_link(link)
  163. def get_ephem_path_for_link(self, link):
  164. # type: (Link) -> str
  165. return self._ephem_cache.get_path_for_link(link)
  166. def get(self, link, package_name):
  167. # type: (Link, Optional[str]) -> Link
  168. retval = self._wheel_cache.get(link, package_name)
  169. if retval is link:
  170. retval = self._ephem_cache.get(link, package_name)
  171. return retval
  172. def cleanup(self):
  173. # type: () -> None
  174. self._wheel_cache.cleanup()
  175. self._ephem_cache.cleanup()