_base.py 19 KB

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