python_dependencies.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. # Copyright 2017 Vector Creations Ltd
  3. # Copyright 2018 New Vector Ltd
  4. # Copyright 2020 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import itertools
  18. import logging
  19. from typing import List, Set
  20. from pkg_resources import (
  21. DistributionNotFound,
  22. Requirement,
  23. VersionConflict,
  24. get_provider,
  25. )
  26. logger = logging.getLogger(__name__)
  27. # REQUIREMENTS is a simple list of requirement specifiers[1], and must be
  28. # installed. It is passed to setup() as install_requires in setup.py.
  29. #
  30. # CONDITIONAL_REQUIREMENTS is the optional dependencies, represented as a dict
  31. # of lists. The dict key is the optional dependency name and can be passed to
  32. # pip when installing. The list is a series of requirement specifiers[1] to be
  33. # installed when that optional dependency requirement is specified. It is passed
  34. # to setup() as extras_require in setup.py
  35. #
  36. # Note that these both represent runtime dependencies (and the versions
  37. # installed are checked at runtime).
  38. #
  39. # Also note that we replicate these constraints in the Synapse Dockerfile while
  40. # pre-installing dependencies. If these constraints are updated here, the same
  41. # change should be made in the Dockerfile.
  42. #
  43. # [1] https://pip.pypa.io/en/stable/reference/pip_install/#requirement-specifiers.
  44. REQUIREMENTS = [
  45. "jsonschema>=2.5.1",
  46. "frozendict>=1",
  47. "unpaddedbase64>=1.1.0",
  48. "canonicaljson>=1.4.0",
  49. # we use the type definitions added in signedjson 1.1.
  50. "signedjson>=1.1.0",
  51. "pynacl>=1.2.1",
  52. "idna>=2.5",
  53. # validating SSL certs for IP addresses requires service_identity 18.1.
  54. "service_identity>=18.1.0",
  55. # Twisted 18.9 introduces some logger improvements that the structured
  56. # logger utilises
  57. "Twisted>=18.9.0",
  58. "treq>=15.1",
  59. # Twisted has required pyopenssl 16.0 since about Twisted 16.6.
  60. "pyopenssl>=16.0.0",
  61. "pyyaml>=3.11",
  62. "pyasn1>=0.1.9",
  63. "pyasn1-modules>=0.0.7",
  64. "bcrypt>=3.1.0",
  65. "pillow>=4.3.0",
  66. "sortedcontainers>=1.4.4",
  67. "pymacaroons>=0.13.0",
  68. "msgpack>=0.5.2",
  69. "phonenumbers>=8.2.0",
  70. # we use GaugeHistogramMetric, which was added in prom-client 0.4.0.
  71. "prometheus_client>=0.4.0",
  72. # we use attr.validators.deep_iterable, which arrived in 19.1.0 (Note:
  73. # Fedora 31 only has 19.1, so if we want to upgrade we should wait until 33
  74. # is out in November.)
  75. "attrs>=19.1.0",
  76. "netaddr>=0.7.18",
  77. "Jinja2>=2.9",
  78. "bleach>=1.4.3",
  79. "typing-extensions>=3.7.4",
  80. # We enforce that we have a `cryptography` version that bundles an `openssl`
  81. # with the latest security patches.
  82. "cryptography>=3.4.7;python_version>='3.6'",
  83. ]
  84. CONDITIONAL_REQUIREMENTS = {
  85. "matrix-synapse-ldap3": ["matrix-synapse-ldap3>=0.1"],
  86. "postgres": [
  87. # we use execute_values with the fetch param, which arrived in psycopg 2.8.
  88. "psycopg2>=2.8 ; platform_python_implementation != 'PyPy'",
  89. "psycopg2cffi>=2.8 ; platform_python_implementation == 'PyPy'",
  90. "psycopg2cffi-compat==1.1 ; platform_python_implementation == 'PyPy'",
  91. ],
  92. # ACME support is required to provision TLS certificates from authorities
  93. # that use the protocol, such as Let's Encrypt.
  94. "acme": [
  95. "txacme>=0.9.2",
  96. # txacme depends on eliot. Eliot 1.8.0 is incompatible with
  97. # python 3.5.2, as per https://github.com/itamarst/eliot/issues/418
  98. "eliot<1.8.0;python_version<'3.5.3'",
  99. ],
  100. "saml2": [
  101. # pysaml2 6.4.0 is incompatible with Python 3.5 (see https://github.com/IdentityPython/pysaml2/issues/749)
  102. "pysaml2>=4.5.0,<6.4.0;python_version<'3.6'",
  103. "pysaml2>=4.5.0;python_version>='3.6'",
  104. ],
  105. "oidc": ["authlib>=0.14.0"],
  106. # systemd-python is necessary for logging to the systemd journal via
  107. # `systemd.journal.JournalHandler`, as is documented in
  108. # `contrib/systemd/log_config.yaml`.
  109. "systemd": ["systemd-python>=231"],
  110. "url_preview": ["lxml>=3.5.0"],
  111. "sentry": ["sentry-sdk>=0.7.2"],
  112. "opentracing": ["jaeger-client>=4.0.0", "opentracing>=2.2.0"],
  113. "jwt": ["pyjwt>=1.6.4"],
  114. # hiredis is not a *strict* dependency, but it makes things much faster.
  115. # (if it is not installed, we fall back to slow code.)
  116. "redis": ["txredisapi>=1.4.7", "hiredis"],
  117. }
  118. ALL_OPTIONAL_REQUIREMENTS = set() # type: Set[str]
  119. for name, optional_deps in CONDITIONAL_REQUIREMENTS.items():
  120. # Exclude systemd as it's a system-based requirement.
  121. # Exclude lint as it's a dev-based requirement.
  122. if name not in ["systemd"]:
  123. ALL_OPTIONAL_REQUIREMENTS = set(optional_deps) | ALL_OPTIONAL_REQUIREMENTS
  124. # ensure there are no double-quote characters in any of the deps (otherwise the
  125. # 'pip install' incantation in DependencyException will break)
  126. for dep in itertools.chain(
  127. REQUIREMENTS,
  128. *CONDITIONAL_REQUIREMENTS.values(),
  129. ):
  130. if '"' in dep:
  131. raise Exception(
  132. "Dependency `%s` contains double-quote; use single-quotes instead" % (dep,)
  133. )
  134. def list_requirements():
  135. return list(set(REQUIREMENTS) | ALL_OPTIONAL_REQUIREMENTS)
  136. class DependencyException(Exception):
  137. @property
  138. def message(self):
  139. return "\n".join(
  140. [
  141. "Missing Requirements: %s" % (", ".join(self.dependencies),),
  142. "To install run:",
  143. " pip install --upgrade --force %s" % (" ".join(self.dependencies),),
  144. "",
  145. ]
  146. )
  147. @property
  148. def dependencies(self):
  149. for i in self.args[0]:
  150. yield '"' + i + '"'
  151. def check_requirements(for_feature=None):
  152. deps_needed = []
  153. errors = []
  154. if for_feature:
  155. reqs = CONDITIONAL_REQUIREMENTS[for_feature]
  156. else:
  157. reqs = REQUIREMENTS
  158. for dependency in reqs:
  159. try:
  160. _check_requirement(dependency)
  161. except VersionConflict as e:
  162. deps_needed.append(dependency)
  163. errors.append(
  164. "Needed %s, got %s==%s"
  165. % (
  166. dependency,
  167. e.dist.project_name, # type: ignore[attr-defined] # noqa
  168. e.dist.version, # type: ignore[attr-defined] # noqa
  169. )
  170. )
  171. except DistributionNotFound:
  172. deps_needed.append(dependency)
  173. if for_feature:
  174. errors.append(
  175. "Needed %s for the '%s' feature but it was not installed"
  176. % (dependency, for_feature)
  177. )
  178. else:
  179. errors.append("Needed %s but it was not installed" % (dependency,))
  180. if not for_feature:
  181. # Check the optional dependencies are up to date. We allow them to not be
  182. # installed.
  183. OPTS = sum(CONDITIONAL_REQUIREMENTS.values(), []) # type: List[str]
  184. for dependency in OPTS:
  185. try:
  186. _check_requirement(dependency)
  187. except VersionConflict as e:
  188. deps_needed.append(dependency)
  189. errors.append(
  190. "Needed optional %s, got %s==%s"
  191. % (
  192. dependency,
  193. e.dist.project_name, # type: ignore[attr-defined] # noqa
  194. e.dist.version, # type: ignore[attr-defined] # noqa
  195. )
  196. )
  197. except DistributionNotFound:
  198. # If it's not found, we don't care
  199. pass
  200. if deps_needed:
  201. for err in errors:
  202. logging.error(err)
  203. raise DependencyException(deps_needed)
  204. def _check_requirement(dependency_string):
  205. """Parses a dependency string, and checks if the specified requirement is installed
  206. Raises:
  207. VersionConflict if the requirement is installed, but with the the wrong version
  208. DistributionNotFound if nothing is found to provide the requirement
  209. """
  210. req = Requirement.parse(dependency_string)
  211. # first check if the markers specify that this requirement needs installing
  212. if req.marker is not None and not req.marker.evaluate():
  213. # not required for this environment
  214. return
  215. get_provider(req)
  216. if __name__ == "__main__":
  217. import sys
  218. sys.stdout.writelines(req + "\n" for req in list_requirements())