cache.py 9.7 KB

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