homeserver.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2014-2016 OpenMarket Ltd
  4. # Copyright 2019 New Vector Ltd
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. from __future__ import print_function
  18. import gc
  19. import logging
  20. import os
  21. import sys
  22. from six import iteritems
  23. import psutil
  24. from prometheus_client import Gauge
  25. from twisted.application import service
  26. from twisted.internet import defer, reactor
  27. from twisted.python.failure import Failure
  28. from twisted.web.resource import EncodingResourceWrapper, NoResource
  29. from twisted.web.server import GzipEncoderFactory
  30. from twisted.web.static import File
  31. import synapse
  32. import synapse.config.logger
  33. from synapse import events
  34. from synapse.api.urls import (
  35. CONTENT_REPO_PREFIX,
  36. FEDERATION_PREFIX,
  37. LEGACY_MEDIA_PREFIX,
  38. MEDIA_PREFIX,
  39. SERVER_KEY_V2_PREFIX,
  40. STATIC_PREFIX,
  41. WEB_CLIENT_PREFIX,
  42. )
  43. from synapse.app import _base
  44. from synapse.app._base import listen_ssl, listen_tcp, quit_with_error
  45. from synapse.config._base import ConfigError
  46. from synapse.config.homeserver import HomeServerConfig
  47. from synapse.federation.transport.server import TransportLayerServer
  48. from synapse.http.additional_resource import AdditionalResource
  49. from synapse.http.server import RootRedirect
  50. from synapse.http.site import SynapseSite
  51. from synapse.logging.context import LoggingContext
  52. from synapse.metrics import METRICS_PREFIX, MetricsResource, RegistryProxy
  53. from synapse.metrics.background_process_metrics import run_as_background_process
  54. from synapse.module_api import ModuleApi
  55. from synapse.python_dependencies import check_requirements
  56. from synapse.replication.http import REPLICATION_PREFIX, ReplicationRestResource
  57. from synapse.replication.tcp.resource import ReplicationStreamProtocolFactory
  58. from synapse.rest import ClientRestResource
  59. from synapse.rest.admin import AdminRestResource
  60. from synapse.rest.key.v2 import KeyApiV2Resource
  61. from synapse.rest.media.v0.content_repository import ContentRepoResource
  62. from synapse.rest.well_known import WellKnownResource
  63. from synapse.server import HomeServer
  64. from synapse.storage import DataStore, are_all_users_on_domain
  65. from synapse.storage.engines import IncorrectDatabaseSetup, create_engine
  66. from synapse.storage.prepare_database import UpgradeDatabaseException, prepare_database
  67. from synapse.util.caches import CACHE_SIZE_FACTOR
  68. from synapse.util.httpresourcetree import create_resource_tree
  69. from synapse.util.manhole import manhole
  70. from synapse.util.module_loader import load_module
  71. from synapse.util.rlimit import change_resource_limit
  72. from synapse.util.versionstring import get_version_string
  73. logger = logging.getLogger("synapse.app.homeserver")
  74. def gz_wrap(r):
  75. return EncodingResourceWrapper(r, [GzipEncoderFactory()])
  76. class SynapseHomeServer(HomeServer):
  77. DATASTORE_CLASS = DataStore
  78. def _listener_http(self, config, listener_config):
  79. port = listener_config["port"]
  80. bind_addresses = listener_config["bind_addresses"]
  81. tls = listener_config.get("tls", False)
  82. site_tag = listener_config.get("tag", port)
  83. resources = {}
  84. for res in listener_config["resources"]:
  85. for name in res["names"]:
  86. if name == "openid" and "federation" in res["names"]:
  87. # Skip loading openid resource if federation is defined
  88. # since federation resource will include openid
  89. continue
  90. resources.update(
  91. self._configure_named_resource(name, res.get("compress", False))
  92. )
  93. additional_resources = listener_config.get("additional_resources", {})
  94. logger.debug("Configuring additional resources: %r", additional_resources)
  95. module_api = ModuleApi(self, self.get_auth_handler())
  96. for path, resmodule in additional_resources.items():
  97. handler_cls, config = load_module(resmodule)
  98. handler = handler_cls(config, module_api)
  99. resources[path] = AdditionalResource(self, handler.handle_request)
  100. # try to find something useful to redirect '/' to
  101. if WEB_CLIENT_PREFIX in resources:
  102. root_resource = RootRedirect(WEB_CLIENT_PREFIX)
  103. elif STATIC_PREFIX in resources:
  104. root_resource = RootRedirect(STATIC_PREFIX)
  105. else:
  106. root_resource = NoResource()
  107. root_resource = create_resource_tree(resources, root_resource)
  108. if tls:
  109. ports = listen_ssl(
  110. bind_addresses,
  111. port,
  112. SynapseSite(
  113. "synapse.access.https.%s" % (site_tag,),
  114. site_tag,
  115. listener_config,
  116. root_resource,
  117. self.version_string,
  118. ),
  119. self.tls_server_context_factory,
  120. reactor=self.get_reactor(),
  121. )
  122. logger.info("Synapse now listening on TCP port %d (TLS)", port)
  123. else:
  124. ports = listen_tcp(
  125. bind_addresses,
  126. port,
  127. SynapseSite(
  128. "synapse.access.http.%s" % (site_tag,),
  129. site_tag,
  130. listener_config,
  131. root_resource,
  132. self.version_string,
  133. ),
  134. reactor=self.get_reactor(),
  135. )
  136. logger.info("Synapse now listening on TCP port %d", port)
  137. return ports
  138. def _configure_named_resource(self, name, compress=False):
  139. """Build a resource map for a named resource
  140. Args:
  141. name (str): named resource: one of "client", "federation", etc
  142. compress (bool): whether to enable gzip compression for this
  143. resource
  144. Returns:
  145. dict[str, Resource]: map from path to HTTP resource
  146. """
  147. resources = {}
  148. if name == "client":
  149. client_resource = ClientRestResource(self)
  150. if compress:
  151. client_resource = gz_wrap(client_resource)
  152. resources.update(
  153. {
  154. "/_matrix/client/api/v1": client_resource,
  155. "/_matrix/client/r0": client_resource,
  156. "/_matrix/client/unstable": client_resource,
  157. "/_matrix/client/v2_alpha": client_resource,
  158. "/_matrix/client/versions": client_resource,
  159. "/.well-known/matrix/client": WellKnownResource(self),
  160. "/_synapse/admin": AdminRestResource(self),
  161. }
  162. )
  163. if self.get_config().saml2_enabled:
  164. from synapse.rest.saml2 import SAML2Resource
  165. resources["/_matrix/saml2"] = SAML2Resource(self)
  166. if name == "consent":
  167. from synapse.rest.consent.consent_resource import ConsentResource
  168. consent_resource = ConsentResource(self)
  169. if compress:
  170. consent_resource = gz_wrap(consent_resource)
  171. resources.update({"/_matrix/consent": consent_resource})
  172. if name == "federation":
  173. resources.update({FEDERATION_PREFIX: TransportLayerServer(self)})
  174. if name == "openid":
  175. resources.update(
  176. {
  177. FEDERATION_PREFIX: TransportLayerServer(
  178. self, servlet_groups=["openid"]
  179. )
  180. }
  181. )
  182. if name in ["static", "client"]:
  183. resources.update(
  184. {
  185. STATIC_PREFIX: File(
  186. os.path.join(os.path.dirname(synapse.__file__), "static")
  187. )
  188. }
  189. )
  190. if name in ["media", "federation", "client"]:
  191. if self.get_config().enable_media_repo:
  192. media_repo = self.get_media_repository_resource()
  193. resources.update(
  194. {
  195. MEDIA_PREFIX: media_repo,
  196. LEGACY_MEDIA_PREFIX: media_repo,
  197. CONTENT_REPO_PREFIX: ContentRepoResource(
  198. self, self.config.uploads_path
  199. ),
  200. }
  201. )
  202. elif name == "media":
  203. raise ConfigError(
  204. "'media' resource conflicts with enable_media_repo=False"
  205. )
  206. if name in ["keys", "federation"]:
  207. resources[SERVER_KEY_V2_PREFIX] = KeyApiV2Resource(self)
  208. if name == "webclient":
  209. webclient_path = self.get_config().web_client_location
  210. if webclient_path is None:
  211. logger.warning(
  212. "Not enabling webclient resource, as web_client_location is unset."
  213. )
  214. else:
  215. # GZip is disabled here due to
  216. # https://twistedmatrix.com/trac/ticket/7678
  217. resources[WEB_CLIENT_PREFIX] = File(webclient_path)
  218. if name == "metrics" and self.get_config().enable_metrics:
  219. resources[METRICS_PREFIX] = MetricsResource(RegistryProxy)
  220. if name == "replication":
  221. resources[REPLICATION_PREFIX] = ReplicationRestResource(self)
  222. return resources
  223. def start_listening(self, listeners):
  224. config = self.get_config()
  225. for listener in listeners:
  226. if listener["type"] == "http":
  227. self._listening_services.extend(self._listener_http(config, listener))
  228. elif listener["type"] == "manhole":
  229. listen_tcp(
  230. listener["bind_addresses"],
  231. listener["port"],
  232. manhole(
  233. username="matrix", password="rabbithole", globals={"hs": self}
  234. ),
  235. )
  236. elif listener["type"] == "replication":
  237. services = listen_tcp(
  238. listener["bind_addresses"],
  239. listener["port"],
  240. ReplicationStreamProtocolFactory(self),
  241. )
  242. for s in services:
  243. reactor.addSystemEventTrigger("before", "shutdown", s.stopListening)
  244. elif listener["type"] == "metrics":
  245. if not self.get_config().enable_metrics:
  246. logger.warn(
  247. (
  248. "Metrics listener configured, but "
  249. "enable_metrics is not True!"
  250. )
  251. )
  252. else:
  253. _base.listen_metrics(listener["bind_addresses"], listener["port"])
  254. else:
  255. logger.warn("Unrecognized listener type: %s", listener["type"])
  256. def run_startup_checks(self, db_conn, database_engine):
  257. all_users_native = are_all_users_on_domain(
  258. db_conn.cursor(), database_engine, self.hostname
  259. )
  260. if not all_users_native:
  261. quit_with_error(
  262. "Found users in database not native to %s!\n"
  263. "You cannot changed a synapse server_name after it's been configured"
  264. % (self.hostname,)
  265. )
  266. try:
  267. database_engine.check_database(db_conn.cursor())
  268. except IncorrectDatabaseSetup as e:
  269. quit_with_error(str(e))
  270. # Gauges to expose monthly active user control metrics
  271. current_mau_gauge = Gauge("synapse_admin_mau:current", "Current MAU")
  272. max_mau_gauge = Gauge("synapse_admin_mau:max", "MAU Limit")
  273. registered_reserved_users_mau_gauge = Gauge(
  274. "synapse_admin_mau:registered_reserved_users",
  275. "Registered users with reserved threepids",
  276. )
  277. def setup(config_options):
  278. """
  279. Args:
  280. config_options_options: The options passed to Synapse. Usually
  281. `sys.argv[1:]`.
  282. Returns:
  283. HomeServer
  284. """
  285. try:
  286. config = HomeServerConfig.load_or_generate_config(
  287. "Synapse Homeserver", config_options
  288. )
  289. except ConfigError as e:
  290. sys.stderr.write("\n" + str(e) + "\n")
  291. sys.exit(1)
  292. if not config:
  293. # If a config isn't returned, and an exception isn't raised, we're just
  294. # generating config files and shouldn't try to continue.
  295. sys.exit(0)
  296. synapse.config.logger.setup_logging(config, use_worker_options=False)
  297. events.USE_FROZEN_DICTS = config.use_frozen_dicts
  298. database_engine = create_engine(config.database_config)
  299. config.database_config["args"]["cp_openfun"] = database_engine.on_new_connection
  300. hs = SynapseHomeServer(
  301. config.server_name,
  302. db_config=config.database_config,
  303. config=config,
  304. version_string="Synapse/" + get_version_string(synapse),
  305. database_engine=database_engine,
  306. )
  307. logger.info("Preparing database: %s...", config.database_config["name"])
  308. try:
  309. with hs.get_db_conn(run_new_connection=False) as db_conn:
  310. prepare_database(db_conn, database_engine, config=config)
  311. database_engine.on_new_connection(db_conn)
  312. hs.run_startup_checks(db_conn, database_engine)
  313. db_conn.commit()
  314. except UpgradeDatabaseException:
  315. sys.stderr.write(
  316. "\nFailed to upgrade database.\n"
  317. "Have you checked for version specific instructions in"
  318. " UPGRADES.rst?\n"
  319. )
  320. sys.exit(1)
  321. logger.info("Database prepared in %s.", config.database_config["name"])
  322. hs.setup()
  323. hs.setup_master()
  324. @defer.inlineCallbacks
  325. def do_acme():
  326. """
  327. Reprovision an ACME certificate, if it's required.
  328. Returns:
  329. Deferred[bool]: Whether the cert has been updated.
  330. """
  331. acme = hs.get_acme_handler()
  332. # Check how long the certificate is active for.
  333. cert_days_remaining = hs.config.is_disk_cert_valid(allow_self_signed=False)
  334. # We want to reprovision if cert_days_remaining is None (meaning no
  335. # certificate exists), or the days remaining number it returns
  336. # is less than our re-registration threshold.
  337. provision = False
  338. if (
  339. cert_days_remaining is None
  340. or cert_days_remaining < hs.config.acme_reprovision_threshold
  341. ):
  342. provision = True
  343. if provision:
  344. yield acme.provision_certificate()
  345. return provision
  346. @defer.inlineCallbacks
  347. def reprovision_acme():
  348. """
  349. Provision a certificate from ACME, if required, and reload the TLS
  350. certificate if it's renewed.
  351. """
  352. reprovisioned = yield do_acme()
  353. if reprovisioned:
  354. _base.refresh_certificate(hs)
  355. @defer.inlineCallbacks
  356. def start():
  357. try:
  358. # Run the ACME provisioning code, if it's enabled.
  359. if hs.config.acme_enabled:
  360. acme = hs.get_acme_handler()
  361. # Start up the webservices which we will respond to ACME
  362. # challenges with, and then provision.
  363. yield acme.start_listening()
  364. yield do_acme()
  365. # Check if it needs to be reprovisioned every day.
  366. hs.get_clock().looping_call(reprovision_acme, 24 * 60 * 60 * 1000)
  367. _base.start(hs, config.listeners)
  368. hs.get_pusherpool().start()
  369. hs.get_datastore().start_doing_background_updates()
  370. except Exception:
  371. # Print the exception and bail out.
  372. print("Error during startup:", file=sys.stderr)
  373. # this gives better tracebacks than traceback.print_exc()
  374. Failure().printTraceback(file=sys.stderr)
  375. if reactor.running:
  376. reactor.stop()
  377. sys.exit(1)
  378. reactor.addSystemEventTrigger("before", "startup", start)
  379. return hs
  380. class SynapseService(service.Service):
  381. """
  382. A twisted Service class that will start synapse. Used to run synapse
  383. via twistd and a .tac.
  384. """
  385. def __init__(self, config):
  386. self.config = config
  387. def startService(self):
  388. hs = setup(self.config)
  389. change_resource_limit(hs.config.soft_file_limit)
  390. if hs.config.gc_thresholds:
  391. gc.set_threshold(*hs.config.gc_thresholds)
  392. def stopService(self):
  393. return self._port.stopListening()
  394. def run(hs):
  395. PROFILE_SYNAPSE = False
  396. if PROFILE_SYNAPSE:
  397. def profile(func):
  398. from cProfile import Profile
  399. from threading import current_thread
  400. def profiled(*args, **kargs):
  401. profile = Profile()
  402. profile.enable()
  403. func(*args, **kargs)
  404. profile.disable()
  405. ident = current_thread().ident
  406. profile.dump_stats(
  407. "/tmp/%s.%s.%i.pstat" % (hs.hostname, func.__name__, ident)
  408. )
  409. return profiled
  410. from twisted.python.threadpool import ThreadPool
  411. ThreadPool._worker = profile(ThreadPool._worker)
  412. reactor.run = profile(reactor.run)
  413. clock = hs.get_clock()
  414. start_time = clock.time()
  415. stats = {}
  416. # Contains the list of processes we will be monitoring
  417. # currently either 0 or 1
  418. stats_process = []
  419. def start_phone_stats_home():
  420. return run_as_background_process("phone_stats_home", phone_stats_home)
  421. @defer.inlineCallbacks
  422. def phone_stats_home():
  423. logger.info("Gathering stats for reporting")
  424. now = int(hs.get_clock().time())
  425. uptime = int(now - start_time)
  426. if uptime < 0:
  427. uptime = 0
  428. stats["homeserver"] = hs.config.server_name
  429. stats["server_context"] = hs.config.server_context
  430. stats["timestamp"] = now
  431. stats["uptime_seconds"] = uptime
  432. version = sys.version_info
  433. stats["python_version"] = "{}.{}.{}".format(
  434. version.major, version.minor, version.micro
  435. )
  436. stats["total_users"] = yield hs.get_datastore().count_all_users()
  437. total_nonbridged_users = yield hs.get_datastore().count_nonbridged_users()
  438. stats["total_nonbridged_users"] = total_nonbridged_users
  439. daily_user_type_results = yield hs.get_datastore().count_daily_user_type()
  440. for name, count in iteritems(daily_user_type_results):
  441. stats["daily_user_type_" + name] = count
  442. room_count = yield hs.get_datastore().get_room_count()
  443. stats["total_room_count"] = room_count
  444. stats["daily_active_users"] = yield hs.get_datastore().count_daily_users()
  445. stats["monthly_active_users"] = yield hs.get_datastore().count_monthly_users()
  446. stats[
  447. "daily_active_rooms"
  448. ] = yield hs.get_datastore().count_daily_active_rooms()
  449. stats["daily_messages"] = yield hs.get_datastore().count_daily_messages()
  450. r30_results = yield hs.get_datastore().count_r30_users()
  451. for name, count in iteritems(r30_results):
  452. stats["r30_users_" + name] = count
  453. daily_sent_messages = yield hs.get_datastore().count_daily_sent_messages()
  454. stats["daily_sent_messages"] = daily_sent_messages
  455. stats["cache_factor"] = CACHE_SIZE_FACTOR
  456. stats["event_cache_size"] = hs.config.event_cache_size
  457. if len(stats_process) > 0:
  458. stats["memory_rss"] = 0
  459. stats["cpu_average"] = 0
  460. for process in stats_process:
  461. stats["memory_rss"] += process.memory_info().rss
  462. stats["cpu_average"] += int(process.cpu_percent(interval=None))
  463. stats["database_engine"] = hs.get_datastore().database_engine_name
  464. stats["database_server_version"] = hs.get_datastore().get_server_version()
  465. logger.info("Reporting stats to matrix.org: %s" % (stats,))
  466. try:
  467. yield hs.get_simple_http_client().put_json(
  468. "https://matrix.org/report-usage-stats/push", stats
  469. )
  470. except Exception as e:
  471. logger.warn("Error reporting stats: %s", e)
  472. def performance_stats_init():
  473. try:
  474. process = psutil.Process()
  475. # Ensure we can fetch both, and make the initial request for cpu_percent
  476. # so the next request will use this as the initial point.
  477. process.memory_info().rss
  478. process.cpu_percent(interval=None)
  479. logger.info("report_stats can use psutil")
  480. stats_process.append(process)
  481. except (AttributeError):
  482. logger.warning("Unable to read memory/cpu stats. Disabling reporting.")
  483. def generate_user_daily_visit_stats():
  484. return run_as_background_process(
  485. "generate_user_daily_visits", hs.get_datastore().generate_user_daily_visits
  486. )
  487. # Rather than update on per session basis, batch up the requests.
  488. # If you increase the loop period, the accuracy of user_daily_visits
  489. # table will decrease
  490. clock.looping_call(generate_user_daily_visit_stats, 5 * 60 * 1000)
  491. # monthly active user limiting functionality
  492. def reap_monthly_active_users():
  493. return run_as_background_process(
  494. "reap_monthly_active_users", hs.get_datastore().reap_monthly_active_users
  495. )
  496. clock.looping_call(reap_monthly_active_users, 1000 * 60 * 60)
  497. reap_monthly_active_users()
  498. @defer.inlineCallbacks
  499. def generate_monthly_active_users():
  500. current_mau_count = 0
  501. reserved_count = 0
  502. store = hs.get_datastore()
  503. if hs.config.limit_usage_by_mau or hs.config.mau_stats_only:
  504. current_mau_count = yield store.get_monthly_active_count()
  505. reserved_count = yield store.get_registered_reserved_users_count()
  506. current_mau_gauge.set(float(current_mau_count))
  507. registered_reserved_users_mau_gauge.set(float(reserved_count))
  508. max_mau_gauge.set(float(hs.config.max_mau_value))
  509. def start_generate_monthly_active_users():
  510. return run_as_background_process(
  511. "generate_monthly_active_users", generate_monthly_active_users
  512. )
  513. start_generate_monthly_active_users()
  514. if hs.config.limit_usage_by_mau or hs.config.mau_stats_only:
  515. clock.looping_call(start_generate_monthly_active_users, 5 * 60 * 1000)
  516. # End of monthly active user settings
  517. if hs.config.report_stats:
  518. logger.info("Scheduling stats reporting for 3 hour intervals")
  519. clock.looping_call(start_phone_stats_home, 3 * 60 * 60 * 1000)
  520. # We need to defer this init for the cases that we daemonize
  521. # otherwise the process ID we get is that of the non-daemon process
  522. clock.call_later(0, performance_stats_init)
  523. # We wait 5 minutes to send the first set of stats as the server can
  524. # be quite busy the first few minutes
  525. clock.call_later(5 * 60, start_phone_stats_home)
  526. _base.start_reactor(
  527. "synapse-homeserver",
  528. soft_file_limit=hs.config.soft_file_limit,
  529. gc_thresholds=hs.config.gc_thresholds,
  530. pid_file=hs.config.pid_file,
  531. daemonize=hs.config.daemonize,
  532. print_pidfile=hs.config.print_pidfile,
  533. logger=logger,
  534. )
  535. def main():
  536. with LoggingContext("main"):
  537. # check base requirements
  538. check_requirements()
  539. hs = setup(sys.argv[1:])
  540. run(hs)
  541. if __name__ == "__main__":
  542. main()