You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

750 lines
26 KiB

  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 signal
  20. import socket
  21. import sys
  22. import traceback
  23. import warnings
  24. from textwrap import indent
  25. from typing import (
  26. TYPE_CHECKING,
  27. Any,
  28. Awaitable,
  29. Callable,
  30. Collection,
  31. Dict,
  32. Iterable,
  33. List,
  34. NoReturn,
  35. Optional,
  36. Tuple,
  37. cast,
  38. )
  39. from cryptography.utils import CryptographyDeprecationWarning
  40. from typing_extensions import ParamSpec
  41. import twisted
  42. from twisted.internet import defer, error, reactor as _reactor
  43. from twisted.internet.interfaces import (
  44. IOpenSSLContextFactory,
  45. IReactorSSL,
  46. IReactorTCP,
  47. IReactorUNIX,
  48. )
  49. from twisted.internet.protocol import ServerFactory
  50. from twisted.internet.tcp import Port
  51. from twisted.logger import LoggingFile, LogLevel
  52. from twisted.protocols.tls import TLSMemoryBIOFactory
  53. from twisted.python.threadpool import ThreadPool
  54. from twisted.web.resource import Resource
  55. import synapse.util.caches
  56. from synapse.api.constants import MAX_PDU_SIZE
  57. from synapse.app import check_bind_error
  58. from synapse.app.phone_stats_home import start_phone_stats_home
  59. from synapse.config import ConfigError
  60. from synapse.config._base import format_config_error
  61. from synapse.config.homeserver import HomeServerConfig
  62. from synapse.config.server import ListenerConfig, ManholeConfig, TCPListenerConfig
  63. from synapse.crypto import context_factory
  64. from synapse.events.presence_router import load_legacy_presence_router
  65. from synapse.handlers.auth import load_legacy_password_auth_providers
  66. from synapse.http.site import SynapseSite
  67. from synapse.logging.context import PreserveLoggingContext
  68. from synapse.logging.opentracing import init_tracer
  69. from synapse.metrics import install_gc_manager, register_threadpool
  70. from synapse.metrics.background_process_metrics import wrap_as_background_process
  71. from synapse.metrics.jemalloc import setup_jemalloc_stats
  72. from synapse.module_api.callbacks.spamchecker_callbacks import load_legacy_spam_checkers
  73. from synapse.module_api.callbacks.third_party_event_rules_callbacks import (
  74. load_legacy_third_party_event_rules,
  75. )
  76. from synapse.types import ISynapseReactor
  77. from synapse.util import SYNAPSE_VERSION
  78. from synapse.util.caches.lrucache import setup_expire_lru_cache_entries
  79. from synapse.util.daemonize import daemonize_process
  80. from synapse.util.gai_resolver import GAIResolver
  81. from synapse.util.rlimit import change_resource_limit
  82. if TYPE_CHECKING:
  83. from synapse.server import HomeServer
  84. # Twisted injects the global reactor to make it easier to import, this confuses
  85. # mypy which thinks it is a module. Tell it that it a more proper type.
  86. reactor = cast(ISynapseReactor, _reactor)
  87. logger = logging.getLogger(__name__)
  88. # list of tuples of function, args list, kwargs dict
  89. _sighup_callbacks: List[
  90. Tuple[Callable[..., None], Tuple[object, ...], Dict[str, object]]
  91. ] = []
  92. P = ParamSpec("P")
  93. def register_sighup(func: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None:
  94. """
  95. Register a function to be called when a SIGHUP occurs.
  96. Args:
  97. func: Function to be called when sent a SIGHUP signal.
  98. *args, **kwargs: args and kwargs to be passed to the target function.
  99. """
  100. _sighup_callbacks.append((func, args, kwargs))
  101. def start_worker_reactor(
  102. appname: str,
  103. config: HomeServerConfig,
  104. # Use a lambda to avoid binding to a given reactor at import time.
  105. # (needed when synapse.app.complement_fork_starter is being used)
  106. run_command: Callable[[], None] = lambda: reactor.run(),
  107. ) -> None:
  108. """Run the reactor in the main process
  109. Daemonizes if necessary, and then configures some resources, before starting
  110. the reactor. Pulls configuration from the 'worker' settings in 'config'.
  111. Args:
  112. appname: application name which will be sent to syslog
  113. config: config object
  114. run_command: callable that actually runs the reactor
  115. """
  116. logger = logging.getLogger(config.worker.worker_app)
  117. start_reactor(
  118. appname,
  119. soft_file_limit=config.server.soft_file_limit,
  120. gc_thresholds=config.server.gc_thresholds,
  121. pid_file=config.worker.worker_pid_file,
  122. daemonize=config.worker.worker_daemonize,
  123. print_pidfile=config.server.print_pidfile,
  124. logger=logger,
  125. run_command=run_command,
  126. )
  127. def start_reactor(
  128. appname: str,
  129. soft_file_limit: int,
  130. gc_thresholds: Optional[Tuple[int, int, int]],
  131. pid_file: Optional[str],
  132. daemonize: bool,
  133. print_pidfile: bool,
  134. logger: logging.Logger,
  135. # Use a lambda to avoid binding to a given reactor at import time.
  136. # (needed when synapse.app.complement_fork_starter is being used)
  137. run_command: Callable[[], None] = lambda: reactor.run(),
  138. ) -> None:
  139. """Run the reactor in the main process
  140. Daemonizes if necessary, and then configures some resources, before starting
  141. the reactor
  142. Args:
  143. appname: application name which will be sent to syslog
  144. soft_file_limit:
  145. gc_thresholds:
  146. pid_file: name of pid file to write to if daemonize is True
  147. daemonize: true to run the reactor in a background process
  148. print_pidfile: whether to print the pid file, if daemonize is True
  149. logger: logger instance to pass to Daemonize
  150. run_command: callable that actually runs the reactor
  151. """
  152. def run() -> None:
  153. logger.info("Running")
  154. setup_jemalloc_stats()
  155. change_resource_limit(soft_file_limit)
  156. if gc_thresholds:
  157. gc.set_threshold(*gc_thresholds)
  158. install_gc_manager()
  159. run_command()
  160. # make sure that we run the reactor with the sentinel log context,
  161. # otherwise other PreserveLoggingContext instances will get confused
  162. # and complain when they see the logcontext arbitrarily swapping
  163. # between the sentinel and `run` logcontexts.
  164. #
  165. # We also need to drop the logcontext before forking if we're daemonizing,
  166. # otherwise the cputime metrics get confused about the per-thread resource usage
  167. # appearing to go backwards.
  168. with PreserveLoggingContext():
  169. if daemonize:
  170. assert pid_file is not None
  171. if print_pidfile:
  172. print(pid_file)
  173. daemonize_process(pid_file, logger)
  174. run()
  175. def quit_with_error(error_string: str) -> NoReturn:
  176. message_lines = error_string.split("\n")
  177. line_length = min(max(len(line) for line in message_lines), 80) + 2
  178. sys.stderr.write("*" * line_length + "\n")
  179. for line in message_lines:
  180. sys.stderr.write(" %s\n" % (line.rstrip(),))
  181. sys.stderr.write("*" * line_length + "\n")
  182. sys.exit(1)
  183. def handle_startup_exception(e: Exception) -> NoReturn:
  184. # Exceptions that occur between setting up the logging and forking or starting
  185. # the reactor are written to the logs, followed by a summary to stderr.
  186. logger.exception("Exception during startup")
  187. error_string = "".join(traceback.format_exception(type(e), e, e.__traceback__))
  188. indented_error_string = indent(error_string, " ")
  189. quit_with_error(
  190. f"Error during initialisation:\n{indented_error_string}\nThere may be more information in the logs."
  191. )
  192. def redirect_stdio_to_logs() -> None:
  193. streams = [("stdout", LogLevel.info), ("stderr", LogLevel.error)]
  194. for stream, level in streams:
  195. oldStream = getattr(sys, stream)
  196. loggingFile = LoggingFile(
  197. logger=twisted.logger.Logger(namespace=stream),
  198. level=level,
  199. encoding=getattr(oldStream, "encoding", None),
  200. )
  201. setattr(sys, stream, loggingFile)
  202. print("Redirected stdout/stderr to logs")
  203. def register_start(
  204. cb: Callable[P, Awaitable], *args: P.args, **kwargs: P.kwargs
  205. ) -> None:
  206. """Register a callback with the reactor, to be called once it is running
  207. This can be used to initialise parts of the system which require an asynchronous
  208. setup.
  209. Any exception raised by the callback will be printed and logged, and the process
  210. will exit.
  211. """
  212. async def wrapper() -> None:
  213. try:
  214. await cb(*args, **kwargs)
  215. except Exception:
  216. # previously, we used Failure().printTraceback() here, in the hope that
  217. # would give better tracebacks than traceback.print_exc(). However, that
  218. # doesn't handle chained exceptions (with a __cause__ or __context__) well,
  219. # and I *think* the need for Failure() is reduced now that we mostly use
  220. # async/await.
  221. # Write the exception to both the logs *and* the unredirected stderr,
  222. # because people tend to get confused if it only goes to one or the other.
  223. #
  224. # One problem with this is that if people are using a logging config that
  225. # logs to the console (as is common eg under docker), they will get two
  226. # copies of the exception. We could maybe try to detect that, but it's
  227. # probably a cost we can bear.
  228. logger.fatal("Error during startup", exc_info=True)
  229. print("Error during startup:", file=sys.__stderr__)
  230. traceback.print_exc(file=sys.__stderr__)
  231. # it's no use calling sys.exit here, since that just raises a SystemExit
  232. # exception which is then caught by the reactor, and everything carries
  233. # on as normal.
  234. os._exit(1)
  235. reactor.callWhenRunning(lambda: defer.ensureDeferred(wrapper()))
  236. def listen_metrics(bind_addresses: Iterable[str], port: int) -> None:
  237. """
  238. Start Prometheus metrics server.
  239. """
  240. from prometheus_client import start_http_server as start_http_server_prometheus
  241. from synapse.metrics import RegistryProxy
  242. for host in bind_addresses:
  243. logger.info("Starting metrics listener on %s:%d", host, port)
  244. _set_prometheus_client_use_created_metrics(False)
  245. start_http_server_prometheus(port, addr=host, registry=RegistryProxy)
  246. def _set_prometheus_client_use_created_metrics(new_value: bool) -> None:
  247. """
  248. Sets whether prometheus_client should expose `_created`-suffixed metrics for
  249. all gauges, histograms and summaries.
  250. There is no programmatic way to disable this without poking at internals;
  251. the proper way is to use an environment variable which prometheus_client
  252. loads at import time.
  253. The motivation for disabling these `_created` metrics is that they're
  254. a waste of space as they're not useful but they take up space in Prometheus.
  255. """
  256. import prometheus_client.metrics
  257. if hasattr(prometheus_client.metrics, "_use_created"):
  258. prometheus_client.metrics._use_created = new_value
  259. else:
  260. logger.error(
  261. "Can't disable `_created` metrics in prometheus_client (brittle hack broken?)"
  262. )
  263. def listen_manhole(
  264. bind_addresses: Collection[str],
  265. port: int,
  266. manhole_settings: ManholeConfig,
  267. manhole_globals: dict,
  268. ) -> None:
  269. # twisted.conch.manhole 21.1.0 uses "int_from_bytes", which produces a confusing
  270. # warning. It's fixed by https://github.com/twisted/twisted/pull/1522), so
  271. # suppress the warning for now.
  272. warnings.filterwarnings(
  273. action="ignore",
  274. category=CryptographyDeprecationWarning,
  275. message="int_from_bytes is deprecated",
  276. )
  277. from synapse.util.manhole import manhole
  278. listen_tcp(
  279. bind_addresses,
  280. port,
  281. manhole(settings=manhole_settings, globals=manhole_globals),
  282. )
  283. def listen_tcp(
  284. bind_addresses: Collection[str],
  285. port: int,
  286. factory: ServerFactory,
  287. reactor: IReactorTCP = reactor,
  288. backlog: int = 50,
  289. ) -> List[Port]:
  290. """
  291. Create a TCP socket for a port and several addresses
  292. Returns:
  293. list of twisted.internet.tcp.Port listening for TCP connections
  294. """
  295. r = []
  296. for address in bind_addresses:
  297. try:
  298. r.append(reactor.listenTCP(port, factory, backlog, address))
  299. except error.CannotListenError as e:
  300. check_bind_error(e, address, bind_addresses)
  301. # IReactorTCP returns an object implementing IListeningPort from listenTCP,
  302. # but we know it will be a Port instance.
  303. return r # type: ignore[return-value]
  304. def listen_unix(
  305. path: str,
  306. mode: int,
  307. factory: ServerFactory,
  308. reactor: IReactorUNIX = reactor,
  309. backlog: int = 50,
  310. ) -> List[Port]:
  311. """
  312. Create a UNIX socket for a given path and 'mode' permission
  313. Returns:
  314. list of twisted.internet.tcp.Port listening for TCP connections
  315. """
  316. wantPID = True
  317. return [
  318. # IReactorUNIX returns an object implementing IListeningPort from listenUNIX,
  319. # but we know it will be a Port instance.
  320. cast(Port, reactor.listenUNIX(path, factory, backlog, mode, wantPID))
  321. ]
  322. def listen_http(
  323. hs: "HomeServer",
  324. listener_config: ListenerConfig,
  325. root_resource: Resource,
  326. version_string: str,
  327. max_request_body_size: int,
  328. context_factory: Optional[IOpenSSLContextFactory],
  329. reactor: ISynapseReactor = reactor,
  330. ) -> List[Port]:
  331. assert listener_config.http_options is not None
  332. site_tag = listener_config.get_site_tag()
  333. site = SynapseSite(
  334. "synapse.access.%s.%s"
  335. % ("https" if listener_config.is_tls() else "http", site_tag),
  336. site_tag,
  337. listener_config,
  338. root_resource,
  339. version_string,
  340. max_request_body_size=max_request_body_size,
  341. reactor=reactor,
  342. hs=hs,
  343. )
  344. if isinstance(listener_config, TCPListenerConfig):
  345. if listener_config.is_tls():
  346. # refresh_certificate should have been called before this.
  347. assert context_factory is not None
  348. ports = listen_ssl(
  349. listener_config.bind_addresses,
  350. listener_config.port,
  351. site,
  352. context_factory,
  353. reactor=reactor,
  354. )
  355. logger.info(
  356. "Synapse now listening on TCP port %d (TLS)", listener_config.port
  357. )
  358. else:
  359. ports = listen_tcp(
  360. listener_config.bind_addresses,
  361. listener_config.port,
  362. site,
  363. reactor=reactor,
  364. )
  365. logger.info("Synapse now listening on TCP port %d", listener_config.port)
  366. else:
  367. ports = listen_unix(
  368. listener_config.path, listener_config.mode, site, reactor=reactor
  369. )
  370. # getHost() returns a UNIXAddress which contains an instance variable of 'name'
  371. # encoded as a byte string. Decode as utf-8 so pretty.
  372. logger.info(
  373. "Synapse now listening on Unix Socket at: "
  374. f"{ports[0].getHost().name.decode('utf-8')}"
  375. )
  376. return ports
  377. def listen_ssl(
  378. bind_addresses: Collection[str],
  379. port: int,
  380. factory: ServerFactory,
  381. context_factory: IOpenSSLContextFactory,
  382. reactor: IReactorSSL = reactor,
  383. backlog: int = 50,
  384. ) -> List[Port]:
  385. """
  386. Create an TLS-over-TCP socket for a port and several addresses
  387. Returns:
  388. list of twisted.internet.tcp.Port listening for TLS connections
  389. """
  390. r = []
  391. for address in bind_addresses:
  392. try:
  393. r.append(
  394. reactor.listenSSL(port, factory, context_factory, backlog, address)
  395. )
  396. except error.CannotListenError as e:
  397. check_bind_error(e, address, bind_addresses)
  398. # IReactorSSL incorrectly declares that an int is returned from listenSSL,
  399. # it actually returns an object implementing IListeningPort, but we know it
  400. # will be a Port instance.
  401. return r # type: ignore[return-value]
  402. def refresh_certificate(hs: "HomeServer") -> None:
  403. """
  404. Refresh the TLS certificates that Synapse is using by re-reading them from
  405. disk and updating the TLS context factories to use them.
  406. """
  407. if not hs.config.server.has_tls_listener():
  408. return
  409. hs.config.tls.read_certificate_from_disk()
  410. hs.tls_server_context_factory = context_factory.ServerContextFactory(hs.config)
  411. if hs._listening_services:
  412. logger.info("Updating context factories...")
  413. for i in hs._listening_services:
  414. # When you listenSSL, it doesn't make an SSL port but a TCP one with
  415. # a TLS wrapping factory around the factory you actually want to get
  416. # requests. This factory attribute is public but missing from
  417. # Twisted's documentation.
  418. if isinstance(i.factory, TLSMemoryBIOFactory):
  419. addr = i.getHost()
  420. logger.info(
  421. "Replacing TLS context factory on [%s]:%i", addr.host, addr.port
  422. )
  423. # We want to replace TLS factories with a new one, with the new
  424. # TLS configuration. We do this by reaching in and pulling out
  425. # the wrappedFactory, and then re-wrapping it.
  426. i.factory = TLSMemoryBIOFactory(
  427. hs.tls_server_context_factory, False, i.factory.wrappedFactory
  428. )
  429. logger.info("Context factories updated.")
  430. async def start(hs: "HomeServer") -> None:
  431. """
  432. Start a Synapse server or worker.
  433. Should be called once the reactor is running.
  434. Will start the main HTTP listeners and do some other startup tasks, and then
  435. notify systemd.
  436. Args:
  437. hs: homeserver instance
  438. """
  439. reactor = hs.get_reactor()
  440. # We want to use a separate thread pool for the resolver so that large
  441. # numbers of DNS requests don't starve out other users of the threadpool.
  442. resolver_threadpool = ThreadPool(name="gai_resolver")
  443. resolver_threadpool.start()
  444. reactor.addSystemEventTrigger("during", "shutdown", resolver_threadpool.stop)
  445. reactor.installNameResolver(
  446. GAIResolver(reactor, getThreadPool=lambda: resolver_threadpool)
  447. )
  448. # Register the threadpools with our metrics.
  449. register_threadpool("default", reactor.getThreadPool())
  450. register_threadpool("gai_resolver", resolver_threadpool)
  451. # Set up the SIGHUP machinery.
  452. if hasattr(signal, "SIGHUP"):
  453. @wrap_as_background_process("sighup")
  454. async def handle_sighup(*args: Any, **kwargs: Any) -> None:
  455. # Tell systemd our state, if we're using it. This will silently fail if
  456. # we're not using systemd.
  457. sdnotify(b"RELOADING=1")
  458. for i, args, kwargs in _sighup_callbacks:
  459. i(*args, **kwargs)
  460. sdnotify(b"READY=1")
  461. # We defer running the sighup handlers until next reactor tick. This
  462. # is so that we're in a sane state, e.g. flushing the logs may fail
  463. # if the sighup happens in the middle of writing a log entry.
  464. def run_sighup(*args: Any, **kwargs: Any) -> None:
  465. # `callFromThread` should be "signal safe" as well as thread
  466. # safe.
  467. reactor.callFromThread(handle_sighup, *args, **kwargs)
  468. signal.signal(signal.SIGHUP, run_sighup)
  469. register_sighup(refresh_certificate, hs)
  470. register_sighup(reload_cache_config, hs.config)
  471. # Apply the cache config.
  472. hs.config.caches.resize_all_caches()
  473. # Load the certificate from disk.
  474. refresh_certificate(hs)
  475. # Start the tracer
  476. init_tracer(hs) # noqa
  477. # Instantiate the modules so they can register their web resources to the module API
  478. # before we start the listeners.
  479. module_api = hs.get_module_api()
  480. for module, config in hs.config.modules.loaded_modules:
  481. m = module(config, module_api)
  482. logger.info("Loaded module %s", m)
  483. load_legacy_spam_checkers(hs)
  484. load_legacy_third_party_event_rules(hs)
  485. load_legacy_presence_router(hs)
  486. load_legacy_password_auth_providers(hs)
  487. # If we've configured an expiry time for caches, start the background job now.
  488. setup_expire_lru_cache_entries(hs)
  489. # It is now safe to start your Synapse.
  490. hs.start_listening()
  491. hs.get_datastores().main.db_pool.start_profiling()
  492. hs.get_pusherpool().start()
  493. # Log when we start the shut down process.
  494. hs.get_reactor().addSystemEventTrigger(
  495. "before", "shutdown", logger.info, "Shutting down..."
  496. )
  497. setup_sentry(hs)
  498. setup_sdnotify(hs)
  499. # If background tasks are running on the main process or this is the worker in
  500. # charge of them, start collecting the phone home stats and shared usage metrics.
  501. if hs.config.worker.run_background_tasks:
  502. await hs.get_common_usage_metrics_manager().setup()
  503. start_phone_stats_home(hs)
  504. # We now freeze all allocated objects in the hopes that (almost)
  505. # everything currently allocated are things that will be used for the
  506. # rest of time. Doing so means less work each GC (hopefully).
  507. #
  508. # PyPy does not (yet?) implement gc.freeze()
  509. if hasattr(gc, "freeze"):
  510. gc.collect()
  511. gc.freeze()
  512. # Speed up shutdowns by freezing all allocated objects. This moves everything
  513. # into the permanent generation and excludes them from the final GC.
  514. atexit.register(gc.freeze)
  515. def reload_cache_config(config: HomeServerConfig) -> None:
  516. """Reload cache config from disk and immediately apply it.resize caches accordingly.
  517. If the config is invalid, a `ConfigError` is logged and no changes are made.
  518. Otherwise, this:
  519. - replaces the `caches` section on the given `config` object,
  520. - resizes all caches according to the new cache factors, and
  521. Note that the following cache config keys are read, but not applied:
  522. - event_cache_size: used to set a max_size and _original_max_size on
  523. EventsWorkerStore._get_event_cache when it is created. We'd have to update
  524. the _original_max_size (and maybe
  525. - sync_response_cache_duration: would have to update the timeout_sec attribute on
  526. HomeServer -> SyncHandler -> ResponseCache.
  527. - track_memory_usage. This affects synapse.util.caches.TRACK_MEMORY_USAGE which
  528. influences Synapse's self-reported metrics.
  529. Also, the HTTPConnectionPool in SimpleHTTPClient sets its maxPersistentPerHost
  530. parameter based on the global_factor. This won't be applied on a config reload.
  531. """
  532. try:
  533. previous_cache_config = config.reload_config_section("caches")
  534. except ConfigError as e:
  535. logger.warning("Failed to reload cache config")
  536. for f in format_config_error(e):
  537. logger.warning(f)
  538. else:
  539. logger.debug(
  540. "New cache config. Was:\n %s\nNow:\n %s",
  541. previous_cache_config.__dict__,
  542. config.caches.__dict__,
  543. )
  544. synapse.util.caches.TRACK_MEMORY_USAGE = config.caches.track_memory_usage
  545. config.caches.resize_all_caches()
  546. def setup_sentry(hs: "HomeServer") -> None:
  547. """Enable sentry integration, if enabled in configuration"""
  548. if not hs.config.metrics.sentry_enabled:
  549. return
  550. import sentry_sdk
  551. sentry_sdk.init(
  552. dsn=hs.config.metrics.sentry_dsn,
  553. release=SYNAPSE_VERSION,
  554. )
  555. # We set some default tags that give some context to this instance
  556. with sentry_sdk.configure_scope() as scope:
  557. scope.set_tag("matrix_server_name", hs.config.server.server_name)
  558. app = (
  559. hs.config.worker.worker_app
  560. if hs.config.worker.worker_app
  561. else "synapse.app.homeserver"
  562. )
  563. name = hs.get_instance_name()
  564. scope.set_tag("worker_app", app)
  565. scope.set_tag("worker_name", name)
  566. def setup_sdnotify(hs: "HomeServer") -> None:
  567. """Adds process state hooks to tell systemd what we are up to."""
  568. # Tell systemd our state, if we're using it. This will silently fail if
  569. # we're not using systemd.
  570. sdnotify(b"READY=1\nMAINPID=%i" % (os.getpid(),))
  571. hs.get_reactor().addSystemEventTrigger(
  572. "before", "shutdown", sdnotify, b"STOPPING=1"
  573. )
  574. sdnotify_sockaddr = os.getenv("NOTIFY_SOCKET")
  575. def sdnotify(state: bytes) -> None:
  576. """
  577. Send a notification to systemd, if the NOTIFY_SOCKET env var is set.
  578. This function is based on the sdnotify python package, but since it's only a few
  579. lines of code, it's easier to duplicate it here than to add a dependency on a
  580. package which many OSes don't include as a matter of principle.
  581. Args:
  582. state: notification to send
  583. """
  584. if not isinstance(state, bytes):
  585. raise TypeError("sdnotify should be called with a bytes")
  586. if not sdnotify_sockaddr:
  587. return
  588. addr = sdnotify_sockaddr
  589. if addr[0] == "@":
  590. addr = "\0" + addr[1:]
  591. try:
  592. with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as sock:
  593. sock.connect(addr)
  594. sock.sendall(state)
  595. except Exception as e:
  596. # this is a bit surprising, since we don't expect to have a NOTIFY_SOCKET
  597. # unless systemd is expecting us to notify it.
  598. logger.warning("Unable to send notification to systemd: %s", e)
  599. def max_request_body_size(config: HomeServerConfig) -> int:
  600. """Get a suitable maximum size for incoming HTTP requests"""
  601. # Other than media uploads, the biggest request we expect to see is a fully-loaded
  602. # /federation/v1/send request.
  603. #
  604. # The main thing in such a request is up to 50 PDUs, and up to 100 EDUs. PDUs are
  605. # limited to 65536 bytes (possibly slightly more if the sender didn't use canonical
  606. # json encoding); there is no specced limit to EDUs (see
  607. # https://github.com/matrix-org/matrix-doc/issues/3121).
  608. #
  609. # in short, we somewhat arbitrarily limit requests to 200 * 64K (about 12.5M)
  610. #
  611. max_request_size = 200 * MAX_PDU_SIZE
  612. # if we have a media repo enabled, we may need to allow larger uploads than that
  613. if config.media.can_load_media_repo:
  614. max_request_size = max(max_request_size, config.media.max_upload_size)
  615. return max_request_size