python_dependencies.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. "cache_memroy": ["pympler"],
  118. }
  119. ALL_OPTIONAL_REQUIREMENTS = set() # type: Set[str]
  120. for name, optional_deps in CONDITIONAL_REQUIREMENTS.items():
  121. # Exclude systemd as it's a system-based requirement.
  122. # Exclude lint as it's a dev-based requirement.
  123. if name not in ["systemd"]:
  124. ALL_OPTIONAL_REQUIREMENTS = set(optional_deps) | ALL_OPTIONAL_REQUIREMENTS
  125. # ensure there are no double-quote characters in any of the deps (otherwise the
  126. # 'pip install' incantation in DependencyException will break)
  127. for dep in itertools.chain(
  128. REQUIREMENTS,
  129. *CONDITIONAL_REQUIREMENTS.values(),
  130. ):
  131. if '"' in dep:
  132. raise Exception(
  133. "Dependency `%s` contains double-quote; use single-quotes instead" % (dep,)
  134. )
  135. def list_requirements():
  136. return list(set(REQUIREMENTS) | ALL_OPTIONAL_REQUIREMENTS)
  137. class DependencyException(Exception):
  138. @property
  139. def message(self):
  140. return "\n".join(
  141. [
  142. "Missing Requirements: %s" % (", ".join(self.dependencies),),
  143. "To install run:",
  144. " pip install --upgrade --force %s" % (" ".join(self.dependencies),),
  145. "",
  146. ]
  147. )
  148. @property
  149. def dependencies(self):
  150. for i in self.args[0]:
  151. yield '"' + i + '"'
  152. def check_requirements(for_feature=None):
  153. deps_needed = []
  154. errors = []
  155. if for_feature:
  156. reqs = CONDITIONAL_REQUIREMENTS[for_feature]
  157. else:
  158. reqs = REQUIREMENTS
  159. for dependency in reqs:
  160. try:
  161. _check_requirement(dependency)
  162. except VersionConflict as e:
  163. deps_needed.append(dependency)
  164. errors.append(
  165. "Needed %s, got %s==%s"
  166. % (
  167. dependency,
  168. e.dist.project_name, # type: ignore[attr-defined] # noqa
  169. e.dist.version, # type: ignore[attr-defined] # noqa
  170. )
  171. )
  172. except DistributionNotFound:
  173. deps_needed.append(dependency)
  174. if for_feature:
  175. errors.append(
  176. "Needed %s for the '%s' feature but it was not installed"
  177. % (dependency, for_feature)
  178. )
  179. else:
  180. errors.append("Needed %s but it was not installed" % (dependency,))
  181. if not for_feature:
  182. # Check the optional dependencies are up to date. We allow them to not be
  183. # installed.
  184. OPTS = sum(CONDITIONAL_REQUIREMENTS.values(), []) # type: List[str]
  185. for dependency in OPTS:
  186. try:
  187. _check_requirement(dependency)
  188. except VersionConflict as e:
  189. deps_needed.append(dependency)
  190. errors.append(
  191. "Needed optional %s, got %s==%s"
  192. % (
  193. dependency,
  194. e.dist.project_name, # type: ignore[attr-defined] # noqa
  195. e.dist.version, # type: ignore[attr-defined] # noqa
  196. )
  197. )
  198. except DistributionNotFound:
  199. # If it's not found, we don't care
  200. pass
  201. if deps_needed:
  202. for err in errors:
  203. logging.error(err)
  204. raise DependencyException(deps_needed)
  205. def _check_requirement(dependency_string):
  206. """Parses a dependency string, and checks if the specified requirement is installed
  207. Raises:
  208. VersionConflict if the requirement is installed, but with the the wrong version
  209. DistributionNotFound if nothing is found to provide the requirement
  210. """
  211. req = Requirement.parse(dependency_string)
  212. # first check if the markers specify that this requirement needs installing
  213. if req.marker is not None and not req.marker.evaluate():
  214. # not required for this environment
  215. return
  216. get_provider(req)
  217. if __name__ == "__main__":
  218. import sys
  219. sys.stdout.writelines(req + "\n" for req in list_requirements())