server.py 14 KB

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