cache.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. """Cache Management
  2. """
  3. import hashlib
  4. import json
  5. import logging
  6. import os
  7. from typing import Any, Dict, List, Optional, Set
  8. from pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version
  9. from pip._vendor.packaging.utils import canonicalize_name
  10. from pip._internal.exceptions import InvalidWheelFilename
  11. from pip._internal.models.format_control import FormatControl
  12. from pip._internal.models.link import Link
  13. from pip._internal.models.wheel import Wheel
  14. from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
  15. from pip._internal.utils.urls import path_to_url
  16. logger = logging.getLogger(__name__)
  17. def _hash_dict(d: Dict[str, str]) -> str:
  18. """Return a stable sha224 of a dictionary."""
  19. s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
  20. return hashlib.sha224(s.encode("ascii")).hexdigest()
  21. class Cache:
  22. """An abstract class - provides cache directories for data from links
  23. :param cache_dir: The root of the cache.
  24. :param format_control: An object of FormatControl class to limit
  25. binaries being read from the cache.
  26. :param allowed_formats: which formats of files the cache should store.
  27. ('binary' and 'source' are the only allowed values)
  28. """
  29. def __init__(
  30. self, cache_dir: str, format_control: FormatControl, allowed_formats: Set[str]
  31. ) -> None:
  32. super().__init__()
  33. assert not cache_dir or os.path.isabs(cache_dir)
  34. self.cache_dir = cache_dir or None
  35. self.format_control = format_control
  36. self.allowed_formats = allowed_formats
  37. _valid_formats = {"source", "binary"}
  38. assert self.allowed_formats.union(_valid_formats) == _valid_formats
  39. def _get_cache_path_parts(self, link: Link) -> List[str]:
  40. """Get parts of part that must be os.path.joined with cache_dir"""
  41. # We want to generate an url to use as our cache key, we don't want to
  42. # just re-use the URL because it might have other items in the fragment
  43. # and we don't care about those.
  44. key_parts = {"url": link.url_without_fragment}
  45. if link.hash_name is not None and link.hash is not None:
  46. key_parts[link.hash_name] = link.hash
  47. if link.subdirectory_fragment:
  48. key_parts["subdirectory"] = link.subdirectory_fragment
  49. # Include interpreter name, major and minor version in cache key
  50. # to cope with ill-behaved sdists that build a different wheel
  51. # depending on the python version their setup.py is being run on,
  52. # and don't encode the difference in compatibility tags.
  53. # https://github.com/pypa/pip/issues/7296
  54. key_parts["interpreter_name"] = interpreter_name()
  55. key_parts["interpreter_version"] = interpreter_version()
  56. # Encode our key url with sha224, we'll use this because it has similar
  57. # security properties to sha256, but with a shorter total output (and
  58. # thus less secure). However the differences don't make a lot of
  59. # difference for our use case here.
  60. hashed = _hash_dict(key_parts)
  61. # We want to nest the directories some to prevent having a ton of top
  62. # level directories where we might run out of sub directories on some
  63. # FS.
  64. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
  65. return parts
  66. def _get_candidates(self, link: Link, canonical_package_name: str) -> List[Any]:
  67. can_not_cache = not self.cache_dir or not canonical_package_name or not link
  68. if can_not_cache:
  69. return []
  70. formats = self.format_control.get_allowed_formats(canonical_package_name)
  71. if not self.allowed_formats.intersection(formats):
  72. return []
  73. candidates = []
  74. path = self.get_path_for_link(link)
  75. if os.path.isdir(path):
  76. for candidate in os.listdir(path):
  77. candidates.append((candidate, path))
  78. return candidates
  79. def get_path_for_link(self, link: Link) -> str:
  80. """Return a directory to store cached items in for link."""
  81. raise NotImplementedError()
  82. def get(
  83. self,
  84. link: Link,
  85. package_name: Optional[str],
  86. supported_tags: List[Tag],
  87. ) -> Link:
  88. """Returns a link to a cached item if it exists, otherwise returns the
  89. passed link.
  90. """
  91. raise NotImplementedError()
  92. class SimpleWheelCache(Cache):
  93. """A cache of wheels for future installs."""
  94. def __init__(self, cache_dir: str, format_control: FormatControl) -> None:
  95. super().__init__(cache_dir, format_control, {"binary"})
  96. def get_path_for_link(self, link: Link) -> str:
  97. """Return a directory to store cached wheels for link
  98. Because there are M wheels for any one sdist, we provide a directory
  99. to cache them in, and then consult that directory when looking up
  100. cache hits.
  101. We only insert things into the cache if they have plausible version
  102. numbers, so that we don't contaminate the cache with things that were
  103. not unique. E.g. ./package might have dozens of installs done for it
  104. and build a version of 0.0...and if we built and cached a wheel, we'd
  105. end up using the same wheel even if the source has been edited.
  106. :param link: The link of the sdist for which this will cache wheels.
  107. """
  108. parts = self._get_cache_path_parts(link)
  109. assert self.cache_dir
  110. # Store wheels within the root cache_dir
  111. return os.path.join(self.cache_dir, "wheels", *parts)
  112. def get(
  113. self,
  114. link: Link,
  115. package_name: Optional[str],
  116. supported_tags: List[Tag],
  117. ) -> Link:
  118. candidates = []
  119. if not package_name:
  120. return link
  121. canonical_package_name = canonicalize_name(package_name)
  122. for wheel_name, wheel_dir in self._get_candidates(link, canonical_package_name):
  123. try:
  124. wheel = Wheel(wheel_name)
  125. except InvalidWheelFilename:
  126. continue
  127. if canonicalize_name(wheel.name) != canonical_package_name:
  128. logger.debug(
  129. "Ignoring cached wheel %s for %s as it "
  130. "does not match the expected distribution name %s.",
  131. wheel_name,
  132. link,
  133. package_name,
  134. )
  135. continue
  136. if not wheel.supported(supported_tags):
  137. # Built for a different python/arch/etc
  138. continue
  139. candidates.append(
  140. (
  141. wheel.support_index_min(supported_tags),
  142. wheel_name,
  143. wheel_dir,
  144. )
  145. )
  146. if not candidates:
  147. return link
  148. _, wheel_name, wheel_dir = min(candidates)
  149. return Link(path_to_url(os.path.join(wheel_dir, wheel_name)))
  150. class EphemWheelCache(SimpleWheelCache):
  151. """A SimpleWheelCache that creates it's own temporary cache directory"""
  152. def __init__(self, format_control: FormatControl) -> None:
  153. self._temp_dir = TempDirectory(
  154. kind=tempdir_kinds.EPHEM_WHEEL_CACHE,
  155. globally_managed=True,
  156. )
  157. super().__init__(self._temp_dir.path, format_control)
  158. class CacheEntry:
  159. def __init__(
  160. self,
  161. link: Link,
  162. persistent: bool,
  163. ):
  164. self.link = link
  165. self.persistent = persistent
  166. class WheelCache(Cache):
  167. """Wraps EphemWheelCache and SimpleWheelCache into a single Cache
  168. This Cache allows for gracefully degradation, using the ephem wheel cache
  169. when a certain link is not found in the simple wheel cache first.
  170. """
  171. def __init__(self, cache_dir: str, format_control: FormatControl) -> None:
  172. super().__init__(cache_dir, format_control, {"binary"})
  173. self._wheel_cache = SimpleWheelCache(cache_dir, format_control)
  174. self._ephem_cache = EphemWheelCache(format_control)
  175. def get_path_for_link(self, link: Link) -> str:
  176. return self._wheel_cache.get_path_for_link(link)
  177. def get_ephem_path_for_link(self, link: Link) -> str:
  178. return self._ephem_cache.get_path_for_link(link)
  179. def get(
  180. self,
  181. link: Link,
  182. package_name: Optional[str],
  183. supported_tags: List[Tag],
  184. ) -> Link:
  185. cache_entry = self.get_cache_entry(link, package_name, supported_tags)
  186. if cache_entry is None:
  187. return link
  188. return cache_entry.link
  189. def get_cache_entry(
  190. self,
  191. link: Link,
  192. package_name: Optional[str],
  193. supported_tags: List[Tag],
  194. ) -> Optional[CacheEntry]:
  195. """Returns a CacheEntry with a link to a cached item if it exists or
  196. None. The cache entry indicates if the item was found in the persistent
  197. or ephemeral cache.
  198. """
  199. retval = self._wheel_cache.get(
  200. link=link,
  201. package_name=package_name,
  202. supported_tags=supported_tags,
  203. )
  204. if retval is not link:
  205. return CacheEntry(retval, persistent=True)
  206. retval = self._ephem_cache.get(
  207. link=link,
  208. package_name=package_name,
  209. supported_tags=supported_tags,
  210. )
  211. if retval is not link:
  212. return CacheEntry(retval, persistent=False)
  213. return None