選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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