self_outdated_check.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. from __future__ import absolute_import
  2. import datetime
  3. import hashlib
  4. import json
  5. import logging
  6. import os.path
  7. import sys
  8. from pip._vendor.packaging import version as packaging_version
  9. from pip._vendor.six import ensure_binary
  10. from pip._internal.index.collector import LinkCollector
  11. from pip._internal.index.package_finder import PackageFinder
  12. from pip._internal.models.selection_prefs import SelectionPreferences
  13. from pip._internal.utils.filesystem import adjacent_tmp_file, check_path_owner, replace
  14. from pip._internal.utils.misc import ensure_dir, get_distribution, get_installed_version
  15. from pip._internal.utils.packaging import get_installer
  16. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  17. if MYPY_CHECK_RUNNING:
  18. import optparse
  19. from typing import Any, Dict, Text, Union
  20. from pip._internal.network.session import PipSession
  21. SELFCHECK_DATE_FMT = "%Y-%m-%dT%H:%M:%SZ"
  22. logger = logging.getLogger(__name__)
  23. def _get_statefile_name(key):
  24. # type: (Union[str, Text]) -> str
  25. key_bytes = ensure_binary(key)
  26. name = hashlib.sha224(key_bytes).hexdigest()
  27. return name
  28. class SelfCheckState(object):
  29. def __init__(self, cache_dir):
  30. # type: (str) -> None
  31. self.state = {} # type: Dict[str, Any]
  32. self.statefile_path = None
  33. # Try to load the existing state
  34. if cache_dir:
  35. self.statefile_path = os.path.join(
  36. cache_dir, "selfcheck", _get_statefile_name(self.key)
  37. )
  38. try:
  39. with open(self.statefile_path) as statefile:
  40. self.state = json.load(statefile)
  41. except (IOError, ValueError, KeyError):
  42. # Explicitly suppressing exceptions, since we don't want to
  43. # error out if the cache file is invalid.
  44. pass
  45. @property
  46. def key(self):
  47. # type: () -> str
  48. return sys.prefix
  49. def save(self, pypi_version, current_time):
  50. # type: (str, datetime.datetime) -> None
  51. # If we do not have a path to cache in, don't bother saving.
  52. if not self.statefile_path:
  53. return
  54. # Check to make sure that we own the directory
  55. if not check_path_owner(os.path.dirname(self.statefile_path)):
  56. return
  57. # Now that we've ensured the directory is owned by this user, we'll go
  58. # ahead and make sure that all our directories are created.
  59. ensure_dir(os.path.dirname(self.statefile_path))
  60. state = {
  61. # Include the key so it's easy to tell which pip wrote the
  62. # file.
  63. "key": self.key,
  64. "last_check": current_time.strftime(SELFCHECK_DATE_FMT),
  65. "pypi_version": pypi_version,
  66. }
  67. text = json.dumps(state, sort_keys=True, separators=(",", ":"))
  68. with adjacent_tmp_file(self.statefile_path) as f:
  69. f.write(ensure_binary(text))
  70. try:
  71. # Since we have a prefix-specific state file, we can just
  72. # overwrite whatever is there, no need to check.
  73. replace(f.name, self.statefile_path)
  74. except OSError:
  75. # Best effort.
  76. pass
  77. def was_installed_by_pip(pkg):
  78. # type: (str) -> bool
  79. """Checks whether pkg was installed by pip
  80. This is used not to display the upgrade message when pip is in fact
  81. installed by system package manager, such as dnf on Fedora.
  82. """
  83. dist = get_distribution(pkg)
  84. if not dist:
  85. return False
  86. return "pip" == get_installer(dist)
  87. def pip_self_version_check(session, options):
  88. # type: (PipSession, optparse.Values) -> None
  89. """Check for an update for pip.
  90. Limit the frequency of checks to once per week. State is stored either in
  91. the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
  92. of the pip script path.
  93. """
  94. installed_version = get_installed_version("pip")
  95. if not installed_version:
  96. return
  97. pip_version = packaging_version.parse(installed_version)
  98. pypi_version = None
  99. try:
  100. state = SelfCheckState(cache_dir=options.cache_dir)
  101. current_time = datetime.datetime.utcnow()
  102. # Determine if we need to refresh the state
  103. if "last_check" in state.state and "pypi_version" in state.state:
  104. last_check = datetime.datetime.strptime(
  105. state.state["last_check"],
  106. SELFCHECK_DATE_FMT
  107. )
  108. if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60:
  109. pypi_version = state.state["pypi_version"]
  110. # Refresh the version if we need to or just see if we need to warn
  111. if pypi_version is None:
  112. # Lets use PackageFinder to see what the latest pip version is
  113. link_collector = LinkCollector.create(
  114. session,
  115. options=options,
  116. suppress_no_index=True,
  117. )
  118. # Pass allow_yanked=False so we don't suggest upgrading to a
  119. # yanked version.
  120. selection_prefs = SelectionPreferences(
  121. allow_yanked=False,
  122. allow_all_prereleases=False, # Explicitly set to False
  123. )
  124. finder = PackageFinder.create(
  125. link_collector=link_collector,
  126. selection_prefs=selection_prefs,
  127. )
  128. best_candidate = finder.find_best_candidate("pip").best_candidate
  129. if best_candidate is None:
  130. return
  131. pypi_version = str(best_candidate.version)
  132. # save that we've performed a check
  133. state.save(pypi_version, current_time)
  134. remote_version = packaging_version.parse(pypi_version)
  135. local_version_is_older = (
  136. pip_version < remote_version and
  137. pip_version.base_version != remote_version.base_version and
  138. was_installed_by_pip('pip')
  139. )
  140. # Determine if our pypi_version is older
  141. if not local_version_is_older:
  142. return
  143. # We cannot tell how the current pip is available in the current
  144. # command context, so be pragmatic here and suggest the command
  145. # that's always available. This does not accommodate spaces in
  146. # `sys.executable`.
  147. pip_cmd = "{} -m pip".format(sys.executable)
  148. logger.warning(
  149. "You are using pip version %s; however, version %s is "
  150. "available.\nYou should consider upgrading via the "
  151. "'%s install --upgrade pip' command.",
  152. pip_version, pypi_version, pip_cmd
  153. )
  154. except Exception:
  155. logger.debug(
  156. "There was an error checking the latest version of pip",
  157. exc_info=True,
  158. )