homeserver.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2019 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. import os
  17. import sys
  18. from typing import Iterator
  19. from twisted.internet import reactor
  20. from twisted.web.resource import EncodingResourceWrapper, IResource
  21. from twisted.web.server import GzipEncoderFactory
  22. from twisted.web.static import File
  23. import synapse
  24. import synapse.config.logger
  25. from synapse import events
  26. from synapse.api.urls import (
  27. FEDERATION_PREFIX,
  28. LEGACY_MEDIA_PREFIX,
  29. MEDIA_PREFIX,
  30. SERVER_KEY_V2_PREFIX,
  31. STATIC_PREFIX,
  32. WEB_CLIENT_PREFIX,
  33. )
  34. from synapse.app import _base
  35. from synapse.app._base import (
  36. handle_startup_exception,
  37. listen_ssl,
  38. listen_tcp,
  39. max_request_body_size,
  40. redirect_stdio_to_logs,
  41. register_start,
  42. )
  43. from synapse.config._base import ConfigError
  44. from synapse.config.emailconfig import ThreepidBehaviour
  45. from synapse.config.homeserver import HomeServerConfig
  46. from synapse.config.server import ListenerConfig
  47. from synapse.federation.transport.server import TransportLayerServer
  48. from synapse.http.additional_resource import AdditionalResource
  49. from synapse.http.server import (
  50. OptionsResource,
  51. RootOptionsRedirectResource,
  52. RootRedirect,
  53. StaticResource,
  54. )
  55. from synapse.http.site import SynapseSite
  56. from synapse.logging.context import LoggingContext
  57. from synapse.metrics import METRICS_PREFIX, MetricsResource, RegistryProxy
  58. from synapse.python_dependencies import check_requirements
  59. from synapse.replication.http import REPLICATION_PREFIX, ReplicationRestResource
  60. from synapse.replication.tcp.resource import ReplicationStreamProtocolFactory
  61. from synapse.rest import ClientRestResource
  62. from synapse.rest.admin import AdminRestResource
  63. from synapse.rest.health import HealthResource
  64. from synapse.rest.key.v2 import KeyApiV2Resource
  65. from synapse.rest.synapse.client import build_synapse_client_resource_tree
  66. from synapse.rest.well_known import well_known_resource
  67. from synapse.server import HomeServer
  68. from synapse.storage import DataStore
  69. from synapse.util.httpresourcetree import create_resource_tree
  70. from synapse.util.module_loader import load_module
  71. from synapse.util.versionstring import get_version_string
  72. logger = logging.getLogger("synapse.app.homeserver")
  73. def gz_wrap(r):
  74. return EncodingResourceWrapper(r, [GzipEncoderFactory()])
  75. class SynapseHomeServer(HomeServer):
  76. DATASTORE_CLASS = DataStore
  77. def _listener_http(self, config: HomeServerConfig, listener_config: ListenerConfig):
  78. port = listener_config.port
  79. bind_addresses = listener_config.bind_addresses
  80. tls = listener_config.tls
  81. site_tag = listener_config.http_options.tag
  82. if site_tag is None:
  83. site_tag = str(port)
  84. # We always include a health resource.
  85. resources = {"/health": HealthResource()}
  86. for res in listener_config.http_options.resources:
  87. for name in res.names:
  88. if name == "openid" and "federation" in res.names:
  89. # Skip loading openid resource if federation is defined
  90. # since federation resource will include openid
  91. continue
  92. resources.update(self._configure_named_resource(name, res.compress))
  93. additional_resources = listener_config.http_options.additional_resources
  94. logger.debug("Configuring additional resources: %r", additional_resources)
  95. module_api = self.get_module_api()
  96. for path, resmodule in additional_resources.items():
  97. handler_cls, config = load_module(
  98. resmodule,
  99. ("listeners", site_tag, "additional_resources", "<%s>" % (path,)),
  100. )
  101. handler = handler_cls(config, module_api)
  102. if IResource.providedBy(handler):
  103. resource = handler
  104. elif hasattr(handler, "handle_request"):
  105. resource = AdditionalResource(self, handler.handle_request)
  106. else:
  107. raise ConfigError(
  108. "additional_resource %s does not implement a known interface"
  109. % (resmodule["module"],)
  110. )
  111. resources[path] = resource
  112. # Attach additional resources registered by modules.
  113. resources.update(self._module_web_resources)
  114. self._module_web_resources_consumed = True
  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": well_known_resource(self),
  171. "/_synapse/admin": AdminRestResource(self),
  172. **build_synapse_client_resource_tree(self),
  173. }
  174. )
  175. if self.config.email.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.server.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.server.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.metrics.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.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,
  257. listener.port,
  258. manhole_settings=self.config.server.manhole_settings,
  259. manhole_globals={"hs": self},
  260. )
  261. elif listener.type == "replication":
  262. services = listen_tcp(
  263. listener.bind_addresses,
  264. listener.port,
  265. ReplicationStreamProtocolFactory(self),
  266. )
  267. for s in services:
  268. reactor.addSystemEventTrigger("before", "shutdown", s.stopListening)
  269. elif listener.type == "metrics":
  270. if not self.config.metrics.enable_metrics:
  271. logger.warning(
  272. "Metrics listener configured, but "
  273. "enable_metrics is not True!"
  274. )
  275. else:
  276. _base.listen_metrics(listener.bind_addresses, listener.port)
  277. else:
  278. # this shouldn't happen, as the listener type should have been checked
  279. # during parsing
  280. logger.warning("Unrecognized listener type: %s", listener.type)
  281. def setup(config_options):
  282. """
  283. Args:
  284. config_options_options: The options passed to Synapse. Usually
  285. `sys.argv[1:]`.
  286. Returns:
  287. HomeServer
  288. """
  289. try:
  290. config = HomeServerConfig.load_or_generate_config(
  291. "Synapse Homeserver", config_options
  292. )
  293. except ConfigError as e:
  294. sys.stderr.write("\n")
  295. for f in format_config_error(e):
  296. sys.stderr.write(f)
  297. sys.stderr.write("\n")
  298. sys.exit(1)
  299. if not config:
  300. # If a config isn't returned, and an exception isn't raised, we're just
  301. # generating config files and shouldn't try to continue.
  302. sys.exit(0)
  303. events.USE_FROZEN_DICTS = config.server.use_frozen_dicts
  304. synapse.util.caches.TRACK_MEMORY_USAGE = config.caches.track_memory_usage
  305. if config.server.gc_seconds:
  306. synapse.metrics.MIN_TIME_BETWEEN_GCS = config.server.gc_seconds
  307. hs = SynapseHomeServer(
  308. config.server.server_name,
  309. config=config,
  310. version_string="Synapse/" + get_version_string(synapse),
  311. )
  312. synapse.config.logger.setup_logging(hs, config, use_worker_options=False)
  313. logger.info("Setting up server")
  314. try:
  315. hs.setup()
  316. except Exception as e:
  317. handle_startup_exception(e)
  318. async def start():
  319. # Load the OIDC provider metadatas, if OIDC is enabled.
  320. if hs.config.oidc.oidc_enabled:
  321. oidc = hs.get_oidc_handler()
  322. # Loading the provider metadata also ensures the provider config is valid.
  323. await oidc.load_metadata()
  324. await _base.start(hs)
  325. hs.get_datastore().db_pool.updates.start_doing_background_updates()
  326. register_start(start)
  327. return hs
  328. def format_config_error(e: ConfigError) -> Iterator[str]:
  329. """
  330. Formats a config error neatly
  331. The idea is to format the immediate error, plus the "causes" of those errors,
  332. hopefully in a way that makes sense to the user. For example:
  333. Error in configuration at 'oidc_config.user_mapping_provider.config.display_name_template':
  334. Failed to parse config for module 'JinjaOidcMappingProvider':
  335. invalid jinja template:
  336. unexpected end of template, expected 'end of print statement'.
  337. Args:
  338. e: the error to be formatted
  339. Returns: An iterator which yields string fragments to be formatted
  340. """
  341. yield "Error in configuration"
  342. if e.path:
  343. yield " at '%s'" % (".".join(e.path),)
  344. yield ":\n %s" % (e.msg,)
  345. e = e.__cause__
  346. indent = 1
  347. while e:
  348. indent += 1
  349. yield ":\n%s%s" % (" " * indent, str(e))
  350. e = e.__cause__
  351. def run(hs: HomeServer):
  352. PROFILE_SYNAPSE = False
  353. if PROFILE_SYNAPSE:
  354. def profile(func):
  355. from cProfile import Profile
  356. from threading import current_thread
  357. def profiled(*args, **kargs):
  358. profile = Profile()
  359. profile.enable()
  360. func(*args, **kargs)
  361. profile.disable()
  362. ident = current_thread().ident
  363. profile.dump_stats(
  364. "/tmp/%s.%s.%i.pstat" % (hs.hostname, func.__name__, ident)
  365. )
  366. return profiled
  367. from twisted.python.threadpool import ThreadPool
  368. ThreadPool._worker = profile(ThreadPool._worker)
  369. reactor.run = profile(reactor.run)
  370. _base.start_reactor(
  371. "synapse-homeserver",
  372. soft_file_limit=hs.config.server.soft_file_limit,
  373. gc_thresholds=hs.config.server.gc_thresholds,
  374. pid_file=hs.config.server.pid_file,
  375. daemonize=hs.config.server.daemonize,
  376. print_pidfile=hs.config.server.print_pidfile,
  377. logger=logger,
  378. )
  379. def main():
  380. with LoggingContext("main"):
  381. # check base requirements
  382. check_requirements()
  383. hs = setup(sys.argv[1:])
  384. # redirect stdio to the logs, if configured.
  385. if not hs.config.logging.no_redirect_stdio:
  386. redirect_stdio_to_logs()
  387. run(hs)
  388. if __name__ == "__main__":
  389. main()