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.
 
 
 
 
 
 

211 lines
7.8 KiB

  1. # Copyright 2022 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. """
  16. This module exposes a single function which checks synapse's dependencies are present
  17. and correctly versioned. It makes use of `importlib.metadata` to do so. The details
  18. are a bit murky: there's no easy way to get a map from "extras" to the packages they
  19. require. But this is probably just symptomatic of Python's package management.
  20. """
  21. import logging
  22. from importlib import metadata
  23. from typing import Iterable, NamedTuple, Optional
  24. from packaging.requirements import Requirement
  25. DISTRIBUTION_NAME = "matrix-synapse"
  26. __all__ = ["check_requirements"]
  27. class DependencyException(Exception):
  28. @property
  29. def message(self) -> str:
  30. return "\n".join(
  31. [
  32. "Missing Requirements: %s" % (", ".join(self.dependencies),),
  33. "To install run:",
  34. " pip install --upgrade --force %s" % (" ".join(self.dependencies),),
  35. "",
  36. ]
  37. )
  38. @property
  39. def dependencies(self) -> Iterable[str]:
  40. for i in self.args[0]:
  41. yield '"' + i + '"'
  42. DEV_EXTRAS = {"lint", "mypy", "test", "dev"}
  43. ALL_EXTRAS = metadata.metadata(DISTRIBUTION_NAME).get_all("Provides-Extra")
  44. assert ALL_EXTRAS is not None
  45. RUNTIME_EXTRAS = set(ALL_EXTRAS) - DEV_EXTRAS
  46. VERSION = metadata.version(DISTRIBUTION_NAME)
  47. def _is_dev_dependency(req: Requirement) -> bool:
  48. return req.marker is not None and any(
  49. req.marker.evaluate({"extra": e}) for e in DEV_EXTRAS
  50. )
  51. def _should_ignore_runtime_requirement(req: Requirement) -> bool:
  52. # This is a build-time dependency. Irritatingly, `poetry build` ignores the
  53. # requirements listed in the [build-system] section of pyproject.toml, so in order
  54. # to support `poetry install --no-dev` we have to mark it as a runtime dependency.
  55. # See discussion on https://github.com/python-poetry/poetry/issues/6154 (it sounds
  56. # like the poetry authors don't consider this a bug?)
  57. #
  58. # In any case, workaround this by ignoring setuptools_rust here. (It might be
  59. # slightly cleaner to put `setuptools_rust` in a `build` extra or similar, but for
  60. # now let's do something quick and dirty.
  61. if req.name == "setuptools_rust":
  62. return True
  63. return False
  64. class Dependency(NamedTuple):
  65. requirement: Requirement
  66. must_be_installed: bool
  67. def _generic_dependencies() -> Iterable[Dependency]:
  68. """Yield pairs (requirement, must_be_installed)."""
  69. requirements = metadata.requires(DISTRIBUTION_NAME)
  70. assert requirements is not None
  71. for raw_requirement in requirements:
  72. req = Requirement(raw_requirement)
  73. if _is_dev_dependency(req) or _should_ignore_runtime_requirement(req):
  74. continue
  75. # https://packaging.pypa.io/en/latest/markers.html#usage notes that
  76. # > Evaluating an extra marker with no environment is an error
  77. # so we pass in a dummy empty extra value here.
  78. must_be_installed = req.marker is None or req.marker.evaluate({"extra": ""})
  79. yield Dependency(req, must_be_installed)
  80. def _dependencies_for_extra(extra: str) -> Iterable[Dependency]:
  81. """Yield additional dependencies needed for a given `extra`."""
  82. requirements = metadata.requires(DISTRIBUTION_NAME)
  83. assert requirements is not None
  84. for raw_requirement in requirements:
  85. req = Requirement(raw_requirement)
  86. if _is_dev_dependency(req):
  87. continue
  88. # Exclude mandatory deps by only selecting deps needed with this extra.
  89. if (
  90. req.marker is not None
  91. and req.marker.evaluate({"extra": extra})
  92. and not req.marker.evaluate({"extra": ""})
  93. ):
  94. yield Dependency(req, True)
  95. def _not_installed(requirement: Requirement, extra: Optional[str] = None) -> str:
  96. if extra:
  97. return (
  98. f"Synapse {VERSION} needs {requirement.name} for {extra}, "
  99. f"but it is not installed"
  100. )
  101. else:
  102. return f"Synapse {VERSION} needs {requirement.name}, but it is not installed"
  103. def _incorrect_version(
  104. requirement: Requirement, got: str, extra: Optional[str] = None
  105. ) -> str:
  106. if extra:
  107. return (
  108. f"Synapse {VERSION} needs {requirement} for {extra}, "
  109. f"but got {requirement.name}=={got}"
  110. )
  111. else:
  112. return (
  113. f"Synapse {VERSION} needs {requirement}, but got {requirement.name}=={got}"
  114. )
  115. def _no_reported_version(requirement: Requirement, extra: Optional[str] = None) -> str:
  116. if extra:
  117. return (
  118. f"Synapse {VERSION} needs {requirement} for {extra}, "
  119. f"but can't determine {requirement.name}'s version"
  120. )
  121. else:
  122. return (
  123. f"Synapse {VERSION} needs {requirement}, "
  124. f"but can't determine {requirement.name}'s version"
  125. )
  126. def check_requirements(extra: Optional[str] = None) -> None:
  127. """Check Synapse's dependencies are present and correctly versioned.
  128. If provided, `extra` must be the name of an pacakging extra (e.g. "saml2" in
  129. `pip install matrix-synapse[saml2]`).
  130. If `extra` is None, this function checks that
  131. - all mandatory dependencies are installed and correctly versioned, and
  132. - each optional dependency that's installed is correctly versioned.
  133. If `extra` is not None, this function checks that
  134. - the dependencies needed for that extra are installed and correctly versioned.
  135. :raises DependencyException: if a dependency is missing or incorrectly versioned.
  136. :raises ValueError: if this extra does not exist.
  137. """
  138. # First work out which dependencies are required, and which are optional.
  139. if extra is None:
  140. dependencies = _generic_dependencies()
  141. elif extra in RUNTIME_EXTRAS:
  142. dependencies = _dependencies_for_extra(extra)
  143. else:
  144. raise ValueError(f"Synapse {VERSION} does not provide the feature '{extra}'")
  145. deps_unfulfilled = []
  146. errors = []
  147. for requirement, must_be_installed in dependencies:
  148. try:
  149. dist: metadata.Distribution = metadata.distribution(requirement.name)
  150. except metadata.PackageNotFoundError:
  151. if must_be_installed:
  152. deps_unfulfilled.append(requirement.name)
  153. errors.append(_not_installed(requirement, extra))
  154. else:
  155. if dist.version is None:
  156. # This shouldn't happen---it suggests a borked virtualenv. (See
  157. # https://github.com/matrix-org/synapse/issues/12223)
  158. # Try to give a vaguely helpful error message anyway.
  159. # Type-ignore: the annotations don't reflect reality: see
  160. # https://github.com/python/typeshed/issues/7513
  161. # https://bugs.python.org/issue47060
  162. deps_unfulfilled.append(requirement.name) # type: ignore[unreachable]
  163. errors.append(_no_reported_version(requirement, extra))
  164. # We specify prereleases=True to allow prereleases such as RCs.
  165. elif not requirement.specifier.contains(dist.version, prereleases=True):
  166. deps_unfulfilled.append(requirement.name)
  167. errors.append(_incorrect_version(requirement, dist.version, extra))
  168. if deps_unfulfilled:
  169. for err in errors:
  170. logging.error(err)
  171. raise DependencyException(deps_unfulfilled)