_base.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. # Copyright 2017 New Vector Ltd
  2. # Copyright 2019-2021 The Matrix.org Foundation C.I.C
  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 atexit
  16. import gc
  17. import logging
  18. import os
  19. import platform
  20. import signal
  21. import socket
  22. import sys
  23. import traceback
  24. import warnings
  25. from typing import TYPE_CHECKING, Awaitable, Callable, Iterable
  26. from cryptography.utils import CryptographyDeprecationWarning
  27. from typing_extensions import NoReturn
  28. import twisted
  29. from twisted.internet import defer, error, reactor
  30. from twisted.logger import LoggingFile, LogLevel
  31. from twisted.protocols.tls import TLSMemoryBIOFactory
  32. import synapse
  33. from synapse.api.constants import MAX_PDU_SIZE
  34. from synapse.app import check_bind_error
  35. from synapse.app.phone_stats_home import start_phone_stats_home
  36. from synapse.config.homeserver import HomeServerConfig
  37. from synapse.config.server import ManholeConfig
  38. from synapse.crypto import context_factory
  39. from synapse.events.presence_router import load_legacy_presence_router
  40. from synapse.events.spamcheck import load_legacy_spam_checkers
  41. from synapse.events.third_party_rules import load_legacy_third_party_event_rules
  42. from synapse.handlers.auth import load_legacy_password_auth_providers
  43. from synapse.logging.context import PreserveLoggingContext
  44. from synapse.metrics.background_process_metrics import wrap_as_background_process
  45. from synapse.metrics.jemalloc import setup_jemalloc_stats
  46. from synapse.util.caches.lrucache import setup_expire_lru_cache_entries
  47. from synapse.util.daemonize import daemonize_process
  48. from synapse.util.rlimit import change_resource_limit
  49. from synapse.util.versionstring import get_version_string
  50. if TYPE_CHECKING:
  51. from synapse.server import HomeServer
  52. logger = logging.getLogger(__name__)
  53. # list of tuples of function, args list, kwargs dict
  54. _sighup_callbacks = []
  55. def register_sighup(func, *args, **kwargs):
  56. """
  57. Register a function to be called when a SIGHUP occurs.
  58. Args:
  59. func (function): Function to be called when sent a SIGHUP signal.
  60. *args, **kwargs: args and kwargs to be passed to the target function.
  61. """
  62. _sighup_callbacks.append((func, args, kwargs))
  63. def start_worker_reactor(appname, config, run_command=reactor.run):
  64. """Run the reactor in the main process
  65. Daemonizes if necessary, and then configures some resources, before starting
  66. the reactor. Pulls configuration from the 'worker' settings in 'config'.
  67. Args:
  68. appname (str): application name which will be sent to syslog
  69. config (synapse.config.Config): config object
  70. run_command (Callable[]): callable that actually runs the reactor
  71. """
  72. logger = logging.getLogger(config.worker.worker_app)
  73. start_reactor(
  74. appname,
  75. soft_file_limit=config.server.soft_file_limit,
  76. gc_thresholds=config.server.gc_thresholds,
  77. pid_file=config.worker.worker_pid_file,
  78. daemonize=config.worker.worker_daemonize,
  79. print_pidfile=config.server.print_pidfile,
  80. logger=logger,
  81. run_command=run_command,
  82. )
  83. def start_reactor(
  84. appname,
  85. soft_file_limit,
  86. gc_thresholds,
  87. pid_file,
  88. daemonize,
  89. print_pidfile,
  90. logger,
  91. run_command=reactor.run,
  92. ):
  93. """Run the reactor in the main process
  94. Daemonizes if necessary, and then configures some resources, before starting
  95. the reactor
  96. Args:
  97. appname (str): application name which will be sent to syslog
  98. soft_file_limit (int):
  99. gc_thresholds:
  100. pid_file (str): name of pid file to write to if daemonize is True
  101. daemonize (bool): true to run the reactor in a background process
  102. print_pidfile (bool): whether to print the pid file, if daemonize is True
  103. logger (logging.Logger): logger instance to pass to Daemonize
  104. run_command (Callable[]): callable that actually runs the reactor
  105. """
  106. def run():
  107. logger.info("Running")
  108. setup_jemalloc_stats()
  109. change_resource_limit(soft_file_limit)
  110. if gc_thresholds:
  111. gc.set_threshold(*gc_thresholds)
  112. run_command()
  113. # make sure that we run the reactor with the sentinel log context,
  114. # otherwise other PreserveLoggingContext instances will get confused
  115. # and complain when they see the logcontext arbitrarily swapping
  116. # between the sentinel and `run` logcontexts.
  117. #
  118. # We also need to drop the logcontext before forking if we're daemonizing,
  119. # otherwise the cputime metrics get confused about the per-thread resource usage
  120. # appearing to go backwards.
  121. with PreserveLoggingContext():
  122. if daemonize:
  123. if print_pidfile:
  124. print(pid_file)
  125. daemonize_process(pid_file, logger)
  126. run()
  127. def quit_with_error(error_string: str) -> NoReturn:
  128. message_lines = error_string.split("\n")
  129. line_length = min(max(len(line) for line in message_lines), 80) + 2
  130. sys.stderr.write("*" * line_length + "\n")
  131. for line in message_lines:
  132. sys.stderr.write(" %s\n" % (line.rstrip(),))
  133. sys.stderr.write("*" * line_length + "\n")
  134. sys.exit(1)
  135. def handle_startup_exception(e: Exception) -> NoReturn:
  136. # Exceptions that occur between setting up the logging and forking or starting
  137. # the reactor are written to the logs, followed by a summary to stderr.
  138. logger.exception("Exception during startup")
  139. quit_with_error(
  140. f"Error during initialisation:\n {e}\nThere may be more information in the logs."
  141. )
  142. def redirect_stdio_to_logs() -> None:
  143. streams = [("stdout", LogLevel.info), ("stderr", LogLevel.error)]
  144. for (stream, level) in streams:
  145. oldStream = getattr(sys, stream)
  146. loggingFile = LoggingFile(
  147. logger=twisted.logger.Logger(namespace=stream),
  148. level=level,
  149. encoding=getattr(oldStream, "encoding", None),
  150. )
  151. setattr(sys, stream, loggingFile)
  152. print("Redirected stdout/stderr to logs")
  153. def register_start(cb: Callable[..., Awaitable], *args, **kwargs) -> None:
  154. """Register a callback with the reactor, to be called once it is running
  155. This can be used to initialise parts of the system which require an asynchronous
  156. setup.
  157. Any exception raised by the callback will be printed and logged, and the process
  158. will exit.
  159. """
  160. async def wrapper():
  161. try:
  162. await cb(*args, **kwargs)
  163. except Exception:
  164. # previously, we used Failure().printTraceback() here, in the hope that
  165. # would give better tracebacks than traceback.print_exc(). However, that
  166. # doesn't handle chained exceptions (with a __cause__ or __context__) well,
  167. # and I *think* the need for Failure() is reduced now that we mostly use
  168. # async/await.
  169. # Write the exception to both the logs *and* the unredirected stderr,
  170. # because people tend to get confused if it only goes to one or the other.
  171. #
  172. # One problem with this is that if people are using a logging config that
  173. # logs to the console (as is common eg under docker), they will get two
  174. # copies of the exception. We could maybe try to detect that, but it's
  175. # probably a cost we can bear.
  176. logger.fatal("Error during startup", exc_info=True)
  177. print("Error during startup:", file=sys.__stderr__)
  178. traceback.print_exc(file=sys.__stderr__)
  179. # it's no use calling sys.exit here, since that just raises a SystemExit
  180. # exception which is then caught by the reactor, and everything carries
  181. # on as normal.
  182. os._exit(1)
  183. reactor.callWhenRunning(lambda: defer.ensureDeferred(wrapper()))
  184. def listen_metrics(bind_addresses, port):
  185. """
  186. Start Prometheus metrics server.
  187. """
  188. from synapse.metrics import RegistryProxy, start_http_server
  189. for host in bind_addresses:
  190. logger.info("Starting metrics listener on %s:%d", host, port)
  191. start_http_server(port, addr=host, registry=RegistryProxy)
  192. def listen_manhole(
  193. bind_addresses: Iterable[str],
  194. port: int,
  195. manhole_settings: ManholeConfig,
  196. manhole_globals: dict,
  197. ):
  198. # twisted.conch.manhole 21.1.0 uses "int_from_bytes", which produces a confusing
  199. # warning. It's fixed by https://github.com/twisted/twisted/pull/1522), so
  200. # suppress the warning for now.
  201. warnings.filterwarnings(
  202. action="ignore",
  203. category=CryptographyDeprecationWarning,
  204. message="int_from_bytes is deprecated",
  205. )
  206. from synapse.util.manhole import manhole
  207. listen_tcp(
  208. bind_addresses,
  209. port,
  210. manhole(settings=manhole_settings, globals=manhole_globals),
  211. )
  212. def listen_tcp(bind_addresses, port, factory, reactor=reactor, backlog=50):
  213. """
  214. Create a TCP socket for a port and several addresses
  215. Returns:
  216. list[twisted.internet.tcp.Port]: listening for TCP connections
  217. """
  218. r = []
  219. for address in bind_addresses:
  220. try:
  221. r.append(reactor.listenTCP(port, factory, backlog, address))
  222. except error.CannotListenError as e:
  223. check_bind_error(e, address, bind_addresses)
  224. return r
  225. def listen_ssl(
  226. bind_addresses, port, factory, context_factory, reactor=reactor, backlog=50
  227. ):
  228. """
  229. Create an TLS-over-TCP socket for a port and several addresses
  230. Returns:
  231. list of twisted.internet.tcp.Port listening for TLS connections
  232. """
  233. r = []
  234. for address in bind_addresses:
  235. try:
  236. r.append(
  237. reactor.listenSSL(port, factory, context_factory, backlog, address)
  238. )
  239. except error.CannotListenError as e:
  240. check_bind_error(e, address, bind_addresses)
  241. return r
  242. def refresh_certificate(hs):
  243. """
  244. Refresh the TLS certificates that Synapse is using by re-reading them from
  245. disk and updating the TLS context factories to use them.
  246. """
  247. if not hs.config.server.has_tls_listener():
  248. return
  249. hs.config.tls.read_certificate_from_disk()
  250. hs.tls_server_context_factory = context_factory.ServerContextFactory(hs.config)
  251. if hs._listening_services:
  252. logger.info("Updating context factories...")
  253. for i in hs._listening_services:
  254. # When you listenSSL, it doesn't make an SSL port but a TCP one with
  255. # a TLS wrapping factory around the factory you actually want to get
  256. # requests. This factory attribute is public but missing from
  257. # Twisted's documentation.
  258. if isinstance(i.factory, TLSMemoryBIOFactory):
  259. addr = i.getHost()
  260. logger.info(
  261. "Replacing TLS context factory on [%s]:%i", addr.host, addr.port
  262. )
  263. # We want to replace TLS factories with a new one, with the new
  264. # TLS configuration. We do this by reaching in and pulling out
  265. # the wrappedFactory, and then re-wrapping it.
  266. i.factory = TLSMemoryBIOFactory(
  267. hs.tls_server_context_factory, False, i.factory.wrappedFactory
  268. )
  269. logger.info("Context factories updated.")
  270. async def start(hs: "HomeServer"):
  271. """
  272. Start a Synapse server or worker.
  273. Should be called once the reactor is running.
  274. Will start the main HTTP listeners and do some other startup tasks, and then
  275. notify systemd.
  276. Args:
  277. hs: homeserver instance
  278. """
  279. # Set up the SIGHUP machinery.
  280. if hasattr(signal, "SIGHUP"):
  281. reactor = hs.get_reactor()
  282. @wrap_as_background_process("sighup")
  283. def handle_sighup(*args, **kwargs):
  284. # Tell systemd our state, if we're using it. This will silently fail if
  285. # we're not using systemd.
  286. sdnotify(b"RELOADING=1")
  287. for i, args, kwargs in _sighup_callbacks:
  288. i(*args, **kwargs)
  289. sdnotify(b"READY=1")
  290. # We defer running the sighup handlers until next reactor tick. This
  291. # is so that we're in a sane state, e.g. flushing the logs may fail
  292. # if the sighup happens in the middle of writing a log entry.
  293. def run_sighup(*args, **kwargs):
  294. # `callFromThread` should be "signal safe" as well as thread
  295. # safe.
  296. reactor.callFromThread(handle_sighup, *args, **kwargs)
  297. signal.signal(signal.SIGHUP, run_sighup)
  298. register_sighup(refresh_certificate, hs)
  299. # Load the certificate from disk.
  300. refresh_certificate(hs)
  301. # Start the tracer
  302. synapse.logging.opentracing.init_tracer(hs) # type: ignore[attr-defined] # noqa
  303. # Instantiate the modules so they can register their web resources to the module API
  304. # before we start the listeners.
  305. module_api = hs.get_module_api()
  306. for module, config in hs.config.modules.loaded_modules:
  307. module(config=config, api=module_api)
  308. load_legacy_spam_checkers(hs)
  309. load_legacy_third_party_event_rules(hs)
  310. load_legacy_presence_router(hs)
  311. load_legacy_password_auth_providers(hs)
  312. # If we've configured an expiry time for caches, start the background job now.
  313. setup_expire_lru_cache_entries(hs)
  314. # It is now safe to start your Synapse.
  315. hs.start_listening()
  316. hs.get_datastore().db_pool.start_profiling()
  317. hs.get_pusherpool().start()
  318. # Log when we start the shut down process.
  319. hs.get_reactor().addSystemEventTrigger(
  320. "before", "shutdown", logger.info, "Shutting down..."
  321. )
  322. setup_sentry(hs)
  323. setup_sdnotify(hs)
  324. # If background tasks are running on the main process, start collecting the
  325. # phone home stats.
  326. if hs.config.worker.run_background_tasks:
  327. start_phone_stats_home(hs)
  328. # We now freeze all allocated objects in the hopes that (almost)
  329. # everything currently allocated are things that will be used for the
  330. # rest of time. Doing so means less work each GC (hopefully).
  331. #
  332. # This only works on Python 3.7
  333. if platform.python_implementation() == "CPython" and sys.version_info >= (3, 7):
  334. gc.collect()
  335. gc.freeze()
  336. # Speed up shutdowns by freezing all allocated objects. This moves everything
  337. # into the permanent generation and excludes them from the final GC.
  338. # Unfortunately only works on Python 3.7
  339. if platform.python_implementation() == "CPython" and sys.version_info >= (3, 7):
  340. atexit.register(gc.freeze)
  341. def setup_sentry(hs):
  342. """Enable sentry integration, if enabled in configuration
  343. Args:
  344. hs (synapse.server.HomeServer)
  345. """
  346. if not hs.config.metrics.sentry_enabled:
  347. return
  348. import sentry_sdk
  349. sentry_sdk.init(
  350. dsn=hs.config.metrics.sentry_dsn, release=get_version_string(synapse)
  351. )
  352. # We set some default tags that give some context to this instance
  353. with sentry_sdk.configure_scope() as scope:
  354. scope.set_tag("matrix_server_name", hs.config.server.server_name)
  355. app = (
  356. hs.config.worker.worker_app
  357. if hs.config.worker.worker_app
  358. else "synapse.app.homeserver"
  359. )
  360. name = hs.get_instance_name()
  361. scope.set_tag("worker_app", app)
  362. scope.set_tag("worker_name", name)
  363. def setup_sdnotify(hs):
  364. """Adds process state hooks to tell systemd what we are up to."""
  365. # Tell systemd our state, if we're using it. This will silently fail if
  366. # we're not using systemd.
  367. sdnotify(b"READY=1\nMAINPID=%i" % (os.getpid(),))
  368. hs.get_reactor().addSystemEventTrigger(
  369. "before", "shutdown", sdnotify, b"STOPPING=1"
  370. )
  371. sdnotify_sockaddr = os.getenv("NOTIFY_SOCKET")
  372. def sdnotify(state):
  373. """
  374. Send a notification to systemd, if the NOTIFY_SOCKET env var is set.
  375. This function is based on the sdnotify python package, but since it's only a few
  376. lines of code, it's easier to duplicate it here than to add a dependency on a
  377. package which many OSes don't include as a matter of principle.
  378. Args:
  379. state (bytes): notification to send
  380. """
  381. if not isinstance(state, bytes):
  382. raise TypeError("sdnotify should be called with a bytes")
  383. if not sdnotify_sockaddr:
  384. return
  385. addr = sdnotify_sockaddr
  386. if addr[0] == "@":
  387. addr = "\0" + addr[1:]
  388. try:
  389. with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as sock:
  390. sock.connect(addr)
  391. sock.sendall(state)
  392. except Exception as e:
  393. # this is a bit surprising, since we don't expect to have a NOTIFY_SOCKET
  394. # unless systemd is expecting us to notify it.
  395. logger.warning("Unable to send notification to systemd: %s", e)
  396. def max_request_body_size(config: HomeServerConfig) -> int:
  397. """Get a suitable maximum size for incoming HTTP requests"""
  398. # Other than media uploads, the biggest request we expect to see is a fully-loaded
  399. # /federation/v1/send request.
  400. #
  401. # The main thing in such a request is up to 50 PDUs, and up to 100 EDUs. PDUs are
  402. # limited to 65536 bytes (possibly slightly more if the sender didn't use canonical
  403. # json encoding); there is no specced limit to EDUs (see
  404. # https://github.com/matrix-org/matrix-doc/issues/3121).
  405. #
  406. # in short, we somewhat arbitrarily limit requests to 200 * 64K (about 12.5M)
  407. #
  408. max_request_size = 200 * MAX_PDU_SIZE
  409. # if we have a media repo enabled, we may need to allow larger uploads than that
  410. if config.media.can_load_media_repo:
  411. max_request_size = max(max_request_size, config.media.max_upload_size)
  412. return max_request_size