server.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2017 New Vector Ltd
  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 logging
  17. from synapse.http.endpoint import parse_and_validate_server_name
  18. from ._base import Config, ConfigError
  19. logger = logging.Logger(__name__)
  20. class ServerConfig(Config):
  21. def read_config(self, config):
  22. self.server_name = config["server_name"]
  23. try:
  24. parse_and_validate_server_name(self.server_name)
  25. except ValueError as e:
  26. raise ConfigError(str(e))
  27. self.pid_file = self.abspath(config.get("pid_file"))
  28. self.web_client = config["web_client"]
  29. self.web_client_location = config.get("web_client_location", None)
  30. self.soft_file_limit = config["soft_file_limit"]
  31. self.daemonize = config.get("daemonize")
  32. self.print_pidfile = config.get("print_pidfile")
  33. self.user_agent_suffix = config.get("user_agent_suffix")
  34. self.use_frozen_dicts = config.get("use_frozen_dicts", False)
  35. self.public_baseurl = config.get("public_baseurl")
  36. self.cpu_affinity = config.get("cpu_affinity")
  37. # Whether to send federation traffic out in this process. This only
  38. # applies to some federation traffic, and so shouldn't be used to
  39. # "disable" federation
  40. self.send_federation = config.get("send_federation", True)
  41. # Whether to update the user directory or not. This should be set to
  42. # false only if we are updating the user directory in a worker
  43. self.update_user_directory = config.get("update_user_directory", True)
  44. # whether to enable the media repository endpoints. This should be set
  45. # to false if the media repository is running as a separate endpoint;
  46. # doing so ensures that we will not run cache cleanup jobs on the
  47. # master, potentially causing inconsistency.
  48. self.enable_media_repo = config.get("enable_media_repo", True)
  49. self.filter_timeline_limit = config.get("filter_timeline_limit", -1)
  50. # Whether we should block invites sent to users on this server
  51. # (other than those sent by local server admins)
  52. self.block_non_admin_invites = config.get(
  53. "block_non_admin_invites", False,
  54. )
  55. # Options to control access by tracking MAU
  56. self.limit_usage_by_mau = config.get("limit_usage_by_mau", False)
  57. self.max_mau_value = 0
  58. if self.limit_usage_by_mau:
  59. self.max_mau_value = config.get(
  60. "max_mau_value", 0,
  61. )
  62. self.mau_limits_reserved_threepids = config.get(
  63. "mau_limit_reserved_threepids", []
  64. )
  65. # Options to disable HS
  66. self.hs_disabled = config.get("hs_disabled", False)
  67. self.hs_disabled_message = config.get("hs_disabled_message", "")
  68. # Admin uri to direct users at should their instance become blocked
  69. # due to resource constraints
  70. self.admin_uri = config.get("admin_uri", None)
  71. # FIXME: federation_domain_whitelist needs sytests
  72. self.federation_domain_whitelist = None
  73. federation_domain_whitelist = config.get(
  74. "federation_domain_whitelist", None
  75. )
  76. # turn the whitelist into a hash for speed of lookup
  77. if federation_domain_whitelist is not None:
  78. self.federation_domain_whitelist = {}
  79. for domain in federation_domain_whitelist:
  80. self.federation_domain_whitelist[domain] = True
  81. if self.public_baseurl is not None:
  82. if self.public_baseurl[-1] != '/':
  83. self.public_baseurl += '/'
  84. self.start_pushers = config.get("start_pushers", True)
  85. self.listeners = config.get("listeners", [])
  86. for listener in self.listeners:
  87. bind_address = listener.pop("bind_address", None)
  88. bind_addresses = listener.setdefault("bind_addresses", [])
  89. if bind_address:
  90. bind_addresses.append(bind_address)
  91. elif not bind_addresses:
  92. bind_addresses.append('')
  93. self.gc_thresholds = read_gc_thresholds(config.get("gc_thresholds", None))
  94. bind_port = config.get("bind_port")
  95. if bind_port:
  96. self.listeners = []
  97. bind_host = config.get("bind_host", "")
  98. gzip_responses = config.get("gzip_responses", True)
  99. names = ["client", "webclient"] if self.web_client else ["client"]
  100. self.listeners.append({
  101. "port": bind_port,
  102. "bind_addresses": [bind_host],
  103. "tls": True,
  104. "type": "http",
  105. "resources": [
  106. {
  107. "names": names,
  108. "compress": gzip_responses,
  109. },
  110. {
  111. "names": ["federation"],
  112. "compress": False,
  113. }
  114. ]
  115. })
  116. unsecure_port = config.get("unsecure_port", bind_port - 400)
  117. if unsecure_port:
  118. self.listeners.append({
  119. "port": unsecure_port,
  120. "bind_addresses": [bind_host],
  121. "tls": False,
  122. "type": "http",
  123. "resources": [
  124. {
  125. "names": names,
  126. "compress": gzip_responses,
  127. },
  128. {
  129. "names": ["federation"],
  130. "compress": False,
  131. }
  132. ]
  133. })
  134. manhole = config.get("manhole")
  135. if manhole:
  136. self.listeners.append({
  137. "port": manhole,
  138. "bind_addresses": ["127.0.0.1"],
  139. "type": "manhole",
  140. })
  141. metrics_port = config.get("metrics_port")
  142. if metrics_port:
  143. logger.warn(
  144. ("The metrics_port configuration option is deprecated in Synapse 0.31 "
  145. "in favour of a listener. Please see "
  146. "http://github.com/matrix-org/synapse/blob/master/docs/metrics-howto.rst"
  147. " on how to configure the new listener."))
  148. self.listeners.append({
  149. "port": metrics_port,
  150. "bind_addresses": [config.get("metrics_bind_host", "127.0.0.1")],
  151. "tls": False,
  152. "type": "http",
  153. "resources": [
  154. {
  155. "names": ["metrics"],
  156. "compress": False,
  157. },
  158. ]
  159. })
  160. def default_config(self, server_name, **kwargs):
  161. _, bind_port = parse_and_validate_server_name(server_name)
  162. if bind_port is not None:
  163. unsecure_port = bind_port - 400
  164. else:
  165. bind_port = 8448
  166. unsecure_port = 8008
  167. pid_file = self.abspath("homeserver.pid")
  168. return """\
  169. ## Server ##
  170. # The domain name of the server, with optional explicit port.
  171. # This is used by remote servers to connect to this server,
  172. # e.g. matrix.org, localhost:8080, etc.
  173. # This is also the last part of your UserID.
  174. server_name: "%(server_name)s"
  175. # When running as a daemon, the file to store the pid in
  176. pid_file: %(pid_file)s
  177. # CPU affinity mask. Setting this restricts the CPUs on which the
  178. # process will be scheduled. It is represented as a bitmask, with the
  179. # lowest order bit corresponding to the first logical CPU and the
  180. # highest order bit corresponding to the last logical CPU. Not all CPUs
  181. # may exist on a given system but a mask may specify more CPUs than are
  182. # present.
  183. #
  184. # For example:
  185. # 0x00000001 is processor #0,
  186. # 0x00000003 is processors #0 and #1,
  187. # 0xFFFFFFFF is all processors (#0 through #31).
  188. #
  189. # Pinning a Python process to a single CPU is desirable, because Python
  190. # is inherently single-threaded due to the GIL, and can suffer a
  191. # 30-40%% slowdown due to cache blow-out and thread context switching
  192. # if the scheduler happens to schedule the underlying threads across
  193. # different cores. See
  194. # https://www.mirantis.com/blog/improve-performance-python-programs-restricting-single-cpu/.
  195. #
  196. # This setting requires the affinity package to be installed!
  197. #
  198. # cpu_affinity: 0xFFFFFFFF
  199. # Whether to serve a web client from the HTTP/HTTPS root resource.
  200. web_client: True
  201. # The root directory to server for the above web client.
  202. # If left undefined, synapse will serve the matrix-angular-sdk web client.
  203. # Make sure matrix-angular-sdk is installed with pip if web_client is True
  204. # and web_client_location is undefined
  205. # web_client_location: "/path/to/web/root"
  206. # The public-facing base URL for the client API (not including _matrix/...)
  207. # public_baseurl: https://example.com:8448/
  208. # Set the soft limit on the number of file descriptors synapse can use
  209. # Zero is used to indicate synapse should set the soft limit to the
  210. # hard limit.
  211. soft_file_limit: 0
  212. # The GC threshold parameters to pass to `gc.set_threshold`, if defined
  213. # gc_thresholds: [700, 10, 10]
  214. # Set the limit on the returned events in the timeline in the get
  215. # and sync operations. The default value is -1, means no upper limit.
  216. # filter_timeline_limit: 5000
  217. # Whether room invites to users on this server should be blocked
  218. # (except those sent by local server admins). The default is False.
  219. # block_non_admin_invites: True
  220. # Restrict federation to the following whitelist of domains.
  221. # N.B. we recommend also firewalling your federation listener to limit
  222. # inbound federation traffic as early as possible, rather than relying
  223. # purely on this application-layer restriction. If not specified, the
  224. # default is to whitelist everything.
  225. #
  226. # federation_domain_whitelist:
  227. # - lon.example.com
  228. # - nyc.example.com
  229. # - syd.example.com
  230. # List of ports that Synapse should listen on, their purpose and their
  231. # configuration.
  232. listeners:
  233. # Main HTTPS listener
  234. # For when matrix traffic is sent directly to synapse.
  235. -
  236. # The port to listen for HTTPS requests on.
  237. port: %(bind_port)s
  238. # Local addresses to listen on.
  239. # On Linux and Mac OS, `::` will listen on all IPv4 and IPv6
  240. # addresses by default. For most other OSes, this will only listen
  241. # on IPv6.
  242. bind_addresses:
  243. - '::'
  244. - '0.0.0.0'
  245. # This is a 'http' listener, allows us to specify 'resources'.
  246. type: http
  247. tls: true
  248. # Use the X-Forwarded-For (XFF) header as the client IP and not the
  249. # actual client IP.
  250. x_forwarded: false
  251. # List of HTTP resources to serve on this listener.
  252. resources:
  253. -
  254. # List of resources to host on this listener.
  255. names:
  256. - client # The client-server APIs, both v1 and v2
  257. - webclient # The bundled webclient.
  258. # Should synapse compress HTTP responses to clients that support it?
  259. # This should be disabled if running synapse behind a load balancer
  260. # that can do automatic compression.
  261. compress: true
  262. - names: [federation] # Federation APIs
  263. compress: false
  264. # optional list of additional endpoints which can be loaded via
  265. # dynamic modules
  266. # additional_resources:
  267. # "/_matrix/my/custom/endpoint":
  268. # module: my_module.CustomRequestHandler
  269. # config: {}
  270. # Unsecure HTTP listener,
  271. # For when matrix traffic passes through loadbalancer that unwraps TLS.
  272. - port: %(unsecure_port)s
  273. tls: false
  274. bind_addresses: ['::', '0.0.0.0']
  275. type: http
  276. x_forwarded: false
  277. resources:
  278. - names: [client, webclient]
  279. compress: true
  280. - names: [federation]
  281. compress: false
  282. # Turn on the twisted ssh manhole service on localhost on the given
  283. # port.
  284. # - port: 9000
  285. # bind_addresses: ['::1', '127.0.0.1']
  286. # type: manhole
  287. """ % locals()
  288. def read_arguments(self, args):
  289. if args.manhole is not None:
  290. self.manhole = args.manhole
  291. if args.daemonize is not None:
  292. self.daemonize = args.daemonize
  293. if args.print_pidfile is not None:
  294. self.print_pidfile = args.print_pidfile
  295. def add_arguments(self, parser):
  296. server_group = parser.add_argument_group("server")
  297. server_group.add_argument("-D", "--daemonize", action='store_true',
  298. default=None,
  299. help="Daemonize the home server")
  300. server_group.add_argument("--print-pidfile", action='store_true',
  301. default=None,
  302. help="Print the path to the pidfile just"
  303. " before daemonizing")
  304. server_group.add_argument("--manhole", metavar="PORT", dest="manhole",
  305. type=int,
  306. help="Turn on the twisted telnet manhole"
  307. " service on the given port.")
  308. def read_gc_thresholds(thresholds):
  309. """Reads the three integer thresholds for garbage collection. Ensures that
  310. the thresholds are integers if thresholds are supplied.
  311. """
  312. if thresholds is None:
  313. return None
  314. try:
  315. assert len(thresholds) == 3
  316. return (
  317. int(thresholds[0]), int(thresholds[1]), int(thresholds[2]),
  318. )
  319. except Exception:
  320. raise ConfigError(
  321. "Value of `gc_threshold` must be a list of three integers if set"
  322. )