_base.py 18 KB

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