homeserver.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. #!/usr/bin/env python
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2019 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. import os
  18. import sys
  19. from typing import Iterator
  20. from twisted.internet import reactor
  21. from twisted.web.resource import EncodingResourceWrapper, IResource
  22. from twisted.web.server import GzipEncoderFactory
  23. from twisted.web.static import File
  24. import synapse
  25. import synapse.config.logger
  26. from synapse import events
  27. from synapse.api.urls import (
  28. FEDERATION_PREFIX,
  29. LEGACY_MEDIA_PREFIX,
  30. MEDIA_PREFIX,
  31. SERVER_KEY_V2_PREFIX,
  32. STATIC_PREFIX,
  33. WEB_CLIENT_PREFIX,
  34. )
  35. from synapse.app import _base
  36. from synapse.app._base import (
  37. listen_ssl,
  38. listen_tcp,
  39. max_request_body_size,
  40. quit_with_error,
  41. redirect_stdio_to_logs,
  42. register_start,
  43. )
  44. from synapse.config._base import ConfigError
  45. from synapse.config.emailconfig import ThreepidBehaviour
  46. from synapse.config.homeserver import HomeServerConfig
  47. from synapse.config.server import ListenerConfig
  48. from synapse.federation.transport.server import TransportLayerServer
  49. from synapse.http.additional_resource import AdditionalResource
  50. from synapse.http.server import (
  51. OptionsResource,
  52. RootOptionsRedirectResource,
  53. RootRedirect,
  54. StaticResource,
  55. )
  56. from synapse.http.site import SynapseSite
  57. from synapse.logging.context import LoggingContext
  58. from synapse.metrics import METRICS_PREFIX, MetricsResource, RegistryProxy
  59. from synapse.python_dependencies import check_requirements
  60. from synapse.replication.http import REPLICATION_PREFIX, ReplicationRestResource
  61. from synapse.replication.tcp.resource import ReplicationStreamProtocolFactory
  62. from synapse.rest import ClientRestResource
  63. from synapse.rest.admin import AdminRestResource
  64. from synapse.rest.health import HealthResource
  65. from synapse.rest.key.v2 import KeyApiV2Resource
  66. from synapse.rest.synapse.client import build_synapse_client_resource_tree
  67. from synapse.rest.well_known import WellKnownResource
  68. from synapse.server import HomeServer
  69. from synapse.storage import DataStore
  70. from synapse.storage.engines import IncorrectDatabaseSetup
  71. from synapse.storage.prepare_database import UpgradeDatabaseException
  72. from synapse.util.httpresourcetree import create_resource_tree
  73. from synapse.util.module_loader import load_module
  74. from synapse.util.versionstring import get_version_string
  75. logger = logging.getLogger("synapse.app.homeserver")
  76. def gz_wrap(r):
  77. return EncodingResourceWrapper(r, [GzipEncoderFactory()])
  78. class SynapseHomeServer(HomeServer):
  79. DATASTORE_CLASS = DataStore
  80. def _listener_http(self, config: HomeServerConfig, listener_config: ListenerConfig):
  81. port = listener_config.port
  82. bind_addresses = listener_config.bind_addresses
  83. tls = listener_config.tls
  84. site_tag = listener_config.http_options.tag
  85. if site_tag is None:
  86. site_tag = str(port)
  87. # We always include a health resource.
  88. resources = {"/health": HealthResource()}
  89. for res in listener_config.http_options.resources:
  90. for name in res.names:
  91. if name == "openid" and "federation" in res.names:
  92. # Skip loading openid resource if federation is defined
  93. # since federation resource will include openid
  94. continue
  95. resources.update(self._configure_named_resource(name, res.compress))
  96. additional_resources = listener_config.http_options.additional_resources
  97. logger.debug("Configuring additional resources: %r", additional_resources)
  98. module_api = self.get_module_api()
  99. for path, resmodule in additional_resources.items():
  100. handler_cls, config = load_module(
  101. resmodule,
  102. ("listeners", site_tag, "additional_resources", "<%s>" % (path,)),
  103. )
  104. handler = handler_cls(config, module_api)
  105. if IResource.providedBy(handler):
  106. resource = handler
  107. elif hasattr(handler, "handle_request"):
  108. resource = AdditionalResource(self, handler.handle_request)
  109. else:
  110. raise ConfigError(
  111. "additional_resource %s does not implement a known interface"
  112. % (resmodule["module"],)
  113. )
  114. resources[path] = resource
  115. # try to find something useful to redirect '/' to
  116. if WEB_CLIENT_PREFIX in resources:
  117. root_resource = RootOptionsRedirectResource(WEB_CLIENT_PREFIX)
  118. elif STATIC_PREFIX in resources:
  119. root_resource = RootOptionsRedirectResource(STATIC_PREFIX)
  120. else:
  121. root_resource = OptionsResource()
  122. site = SynapseSite(
  123. "synapse.access.%s.%s" % ("https" if tls else "http", site_tag),
  124. site_tag,
  125. listener_config,
  126. create_resource_tree(resources, root_resource),
  127. self.version_string,
  128. max_request_body_size=max_request_body_size(self.config),
  129. reactor=self.get_reactor(),
  130. )
  131. if tls:
  132. ports = listen_ssl(
  133. bind_addresses,
  134. port,
  135. site,
  136. self.tls_server_context_factory,
  137. reactor=self.get_reactor(),
  138. )
  139. logger.info("Synapse now listening on TCP port %d (TLS)", port)
  140. else:
  141. ports = listen_tcp(
  142. bind_addresses,
  143. port,
  144. site,
  145. reactor=self.get_reactor(),
  146. )
  147. logger.info("Synapse now listening on TCP port %d", port)
  148. return ports
  149. def _configure_named_resource(self, name, compress=False):
  150. """Build a resource map for a named resource
  151. Args:
  152. name (str): named resource: one of "client", "federation", etc
  153. compress (bool): whether to enable gzip compression for this
  154. resource
  155. Returns:
  156. dict[str, Resource]: map from path to HTTP resource
  157. """
  158. resources = {}
  159. if name == "client":
  160. client_resource = ClientRestResource(self)
  161. if compress:
  162. client_resource = gz_wrap(client_resource)
  163. resources.update(
  164. {
  165. "/_matrix/client/api/v1": client_resource,
  166. "/_matrix/client/r0": client_resource,
  167. "/_matrix/client/unstable": client_resource,
  168. "/_matrix/client/v2_alpha": client_resource,
  169. "/_matrix/client/versions": client_resource,
  170. "/.well-known/matrix/client": WellKnownResource(self),
  171. "/_synapse/admin": AdminRestResource(self),
  172. **build_synapse_client_resource_tree(self),
  173. }
  174. )
  175. if self.config.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
  176. from synapse.rest.synapse.client.password_reset import (
  177. PasswordResetSubmitTokenResource,
  178. )
  179. resources[
  180. "/_synapse/client/password_reset/email/submit_token"
  181. ] = PasswordResetSubmitTokenResource(self)
  182. if name == "consent":
  183. from synapse.rest.consent.consent_resource import ConsentResource
  184. consent_resource = ConsentResource(self)
  185. if compress:
  186. consent_resource = gz_wrap(consent_resource)
  187. resources.update({"/_matrix/consent": consent_resource})
  188. if name == "federation":
  189. resources.update({FEDERATION_PREFIX: TransportLayerServer(self)})
  190. if name == "openid":
  191. resources.update(
  192. {
  193. FEDERATION_PREFIX: TransportLayerServer(
  194. self, servlet_groups=["openid"]
  195. )
  196. }
  197. )
  198. if name in ["static", "client"]:
  199. resources.update(
  200. {
  201. STATIC_PREFIX: StaticResource(
  202. os.path.join(os.path.dirname(synapse.__file__), "static")
  203. )
  204. }
  205. )
  206. if name in ["media", "federation", "client"]:
  207. if self.config.enable_media_repo:
  208. media_repo = self.get_media_repository_resource()
  209. resources.update(
  210. {MEDIA_PREFIX: media_repo, LEGACY_MEDIA_PREFIX: media_repo}
  211. )
  212. elif name == "media":
  213. raise ConfigError(
  214. "'media' resource conflicts with enable_media_repo=False"
  215. )
  216. if name in ["keys", "federation"]:
  217. resources[SERVER_KEY_V2_PREFIX] = KeyApiV2Resource(self)
  218. if name == "webclient":
  219. webclient_loc = self.config.web_client_location
  220. if webclient_loc is None:
  221. logger.warning(
  222. "Not enabling webclient resource, as web_client_location is unset."
  223. )
  224. elif webclient_loc.startswith("http://") or webclient_loc.startswith(
  225. "https://"
  226. ):
  227. resources[WEB_CLIENT_PREFIX] = RootRedirect(webclient_loc)
  228. else:
  229. logger.warning(
  230. "Running webclient on the same domain is not recommended: "
  231. "https://github.com/matrix-org/synapse#security-note - "
  232. "after you move webclient to different host you can set "
  233. "web_client_location to its full URL to enable redirection."
  234. )
  235. # GZip is disabled here due to
  236. # https://twistedmatrix.com/trac/ticket/7678
  237. resources[WEB_CLIENT_PREFIX] = File(webclient_loc)
  238. if name == "metrics" and self.config.enable_metrics:
  239. resources[METRICS_PREFIX] = MetricsResource(RegistryProxy)
  240. if name == "replication":
  241. resources[REPLICATION_PREFIX] = ReplicationRestResource(self)
  242. return resources
  243. def start_listening(self):
  244. if self.config.redis_enabled:
  245. # If redis is enabled we connect via the replication command handler
  246. # in the same way as the workers (since we're effectively a client
  247. # rather than a server).
  248. self.get_tcp_replication().start_replication(self)
  249. for listener in self.config.server.listeners:
  250. if listener.type == "http":
  251. self._listening_services.extend(
  252. self._listener_http(self.config, listener)
  253. )
  254. elif listener.type == "manhole":
  255. _base.listen_manhole(
  256. listener.bind_addresses, listener.port, manhole_globals={"hs": self}
  257. )
  258. elif listener.type == "replication":
  259. services = listen_tcp(
  260. listener.bind_addresses,
  261. listener.port,
  262. ReplicationStreamProtocolFactory(self),
  263. )
  264. for s in services:
  265. reactor.addSystemEventTrigger("before", "shutdown", s.stopListening)
  266. elif listener.type == "metrics":
  267. if not self.config.enable_metrics:
  268. logger.warning(
  269. (
  270. "Metrics listener configured, but "
  271. "enable_metrics is not True!"
  272. )
  273. )
  274. else:
  275. _base.listen_metrics(listener.bind_addresses, listener.port)
  276. else:
  277. # this shouldn't happen, as the listener type should have been checked
  278. # during parsing
  279. logger.warning("Unrecognized listener type: %s", listener.type)
  280. def setup(config_options):
  281. """
  282. Args:
  283. config_options_options: The options passed to Synapse. Usually
  284. `sys.argv[1:]`.
  285. Returns:
  286. HomeServer
  287. """
  288. try:
  289. config = HomeServerConfig.load_or_generate_config(
  290. "Synapse Homeserver", config_options
  291. )
  292. except ConfigError as e:
  293. sys.stderr.write("\n")
  294. for f in format_config_error(e):
  295. sys.stderr.write(f)
  296. sys.stderr.write("\n")
  297. sys.exit(1)
  298. if not config:
  299. # If a config isn't returned, and an exception isn't raised, we're just
  300. # generating config files and shouldn't try to continue.
  301. sys.exit(0)
  302. events.USE_FROZEN_DICTS = config.use_frozen_dicts
  303. synapse.util.caches.TRACK_MEMORY_USAGE = config.caches.track_memory_usage
  304. if config.server.gc_seconds:
  305. synapse.metrics.MIN_TIME_BETWEEN_GCS = config.server.gc_seconds
  306. hs = SynapseHomeServer(
  307. config.server_name,
  308. config=config,
  309. version_string="Synapse/" + get_version_string(synapse),
  310. )
  311. synapse.config.logger.setup_logging(hs, config, use_worker_options=False)
  312. logger.info("Setting up server")
  313. try:
  314. hs.setup()
  315. except IncorrectDatabaseSetup as e:
  316. quit_with_error(str(e))
  317. except UpgradeDatabaseException as e:
  318. quit_with_error("Failed to upgrade database: %s" % (e,))
  319. async def do_acme() -> bool:
  320. """
  321. Reprovision an ACME certificate, if it's required.
  322. Returns:
  323. Whether the cert has been updated.
  324. """
  325. acme = hs.get_acme_handler()
  326. # Check how long the certificate is active for.
  327. cert_days_remaining = hs.config.is_disk_cert_valid(allow_self_signed=False)
  328. # We want to reprovision if cert_days_remaining is None (meaning no
  329. # certificate exists), or the days remaining number it returns
  330. # is less than our re-registration threshold.
  331. provision = False
  332. if (
  333. cert_days_remaining is None
  334. or cert_days_remaining < hs.config.acme_reprovision_threshold
  335. ):
  336. provision = True
  337. if provision:
  338. await acme.provision_certificate()
  339. return provision
  340. async def reprovision_acme():
  341. """
  342. Provision a certificate from ACME, if required, and reload the TLS
  343. certificate if it's renewed.
  344. """
  345. reprovisioned = await do_acme()
  346. if reprovisioned:
  347. _base.refresh_certificate(hs)
  348. async def start():
  349. # Run the ACME provisioning code, if it's enabled.
  350. if hs.config.acme_enabled:
  351. acme = hs.get_acme_handler()
  352. # Start up the webservices which we will respond to ACME
  353. # challenges with, and then provision.
  354. await acme.start_listening()
  355. await do_acme()
  356. # Check if it needs to be reprovisioned every day.
  357. hs.get_clock().looping_call(reprovision_acme, 24 * 60 * 60 * 1000)
  358. # Load the OIDC provider metadatas, if OIDC is enabled.
  359. if hs.config.oidc_enabled:
  360. oidc = hs.get_oidc_handler()
  361. # Loading the provider metadata also ensures the provider config is valid.
  362. await oidc.load_metadata()
  363. await _base.start(hs)
  364. hs.get_datastore().db_pool.updates.start_doing_background_updates()
  365. register_start(start)
  366. return hs
  367. def format_config_error(e: ConfigError) -> Iterator[str]:
  368. """
  369. Formats a config error neatly
  370. The idea is to format the immediate error, plus the "causes" of those errors,
  371. hopefully in a way that makes sense to the user. For example:
  372. Error in configuration at 'oidc_config.user_mapping_provider.config.display_name_template':
  373. Failed to parse config for module 'JinjaOidcMappingProvider':
  374. invalid jinja template:
  375. unexpected end of template, expected 'end of print statement'.
  376. Args:
  377. e: the error to be formatted
  378. Returns: An iterator which yields string fragments to be formatted
  379. """
  380. yield "Error in configuration"
  381. if e.path:
  382. yield " at '%s'" % (".".join(e.path),)
  383. yield ":\n %s" % (e.msg,)
  384. e = e.__cause__
  385. indent = 1
  386. while e:
  387. indent += 1
  388. yield ":\n%s%s" % (" " * indent, str(e))
  389. e = e.__cause__
  390. def run(hs):
  391. PROFILE_SYNAPSE = False
  392. if PROFILE_SYNAPSE:
  393. def profile(func):
  394. from cProfile import Profile
  395. from threading import current_thread
  396. def profiled(*args, **kargs):
  397. profile = Profile()
  398. profile.enable()
  399. func(*args, **kargs)
  400. profile.disable()
  401. ident = current_thread().ident
  402. profile.dump_stats(
  403. "/tmp/%s.%s.%i.pstat" % (hs.hostname, func.__name__, ident)
  404. )
  405. return profiled
  406. from twisted.python.threadpool import ThreadPool
  407. ThreadPool._worker = profile(ThreadPool._worker)
  408. reactor.run = profile(reactor.run)
  409. _base.start_reactor(
  410. "synapse-homeserver",
  411. soft_file_limit=hs.config.soft_file_limit,
  412. gc_thresholds=hs.config.gc_thresholds,
  413. pid_file=hs.config.pid_file,
  414. daemonize=hs.config.daemonize,
  415. print_pidfile=hs.config.print_pidfile,
  416. logger=logger,
  417. )
  418. def main():
  419. with LoggingContext("main"):
  420. # check base requirements
  421. check_requirements()
  422. hs = setup(sys.argv[1:])
  423. # redirect stdio to the logs, if configured.
  424. if not hs.config.no_redirect_stdio:
  425. redirect_stdio_to_logs()
  426. run(hs)
  427. if __name__ == "__main__":
  428. main()