server.py 14 KB

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