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.
 
 
 
 
 
 

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