_base.py 17 KB

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