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.
 
 
 
 
 
 

548 regels
22 KiB

  1. # Copyright 2016 OpenMarket Ltd
  2. # Copyright 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 argparse
  16. import logging
  17. from typing import Any, Dict, List, Union
  18. import attr
  19. from pydantic import BaseModel, Extra, StrictBool, StrictInt, StrictStr
  20. from synapse.config._base import (
  21. Config,
  22. ConfigError,
  23. RoutableShardedWorkerHandlingConfig,
  24. ShardedWorkerHandlingConfig,
  25. )
  26. from synapse.config._util import parse_and_validate_mapping
  27. from synapse.config.server import (
  28. DIRECT_TCP_ERROR,
  29. TCPListenerConfig,
  30. parse_listener_def,
  31. )
  32. from synapse.types import JsonDict
  33. _DEPRECATED_WORKER_DUTY_OPTION_USED = """
  34. The '%s' configuration option is deprecated and will be removed in a future
  35. Synapse version. Please use ``%s: name_of_worker`` instead.
  36. """
  37. _MISSING_MAIN_PROCESS_INSTANCE_MAP_DATA = """
  38. Missing data for a worker to connect to main process. Please include '%s' in the
  39. `instance_map` declared in your shared yaml configuration as defined in configuration
  40. documentation here:
  41. `https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#instance_map`
  42. """
  43. WORKER_REPLICATION_SETTING_DEPRECATED_MESSAGE = """
  44. '%s' is no longer a supported worker setting, please place '%s' onto your shared
  45. configuration under `main` inside the `instance_map`. See workers documentation here:
  46. `https://matrix-org.github.io/synapse/latest/workers.html#worker-configuration`
  47. """
  48. # This allows for a handy knob when it's time to change from 'master' to
  49. # something with less 'history'
  50. MAIN_PROCESS_INSTANCE_NAME = "master"
  51. # Use this to adjust what the main process is known as in the yaml instance_map
  52. MAIN_PROCESS_INSTANCE_MAP_NAME = "main"
  53. logger = logging.getLogger(__name__)
  54. def _instance_to_list_converter(obj: Union[str, List[str]]) -> List[str]:
  55. """Helper for allowing parsing a string or list of strings to a config
  56. option expecting a list of strings.
  57. """
  58. if isinstance(obj, str):
  59. return [obj]
  60. return obj
  61. class ConfigModel(BaseModel):
  62. """A custom version of Pydantic's BaseModel which
  63. - ignores unknown fields and
  64. - does not allow fields to be overwritten after construction,
  65. but otherwise uses Pydantic's default behaviour.
  66. For now, ignore unknown fields. In the future, we could change this so that unknown
  67. config values cause a ValidationError, provided the error messages are meaningful to
  68. server operators.
  69. Subclassing in this way is recommended by
  70. https://pydantic-docs.helpmanual.io/usage/model_config/#change-behaviour-globally
  71. """
  72. class Config:
  73. # By default, ignore fields that we don't recognise.
  74. extra = Extra.ignore
  75. # By default, don't allow fields to be reassigned after parsing.
  76. allow_mutation = False
  77. class InstanceTcpLocationConfig(ConfigModel):
  78. """The host and port to talk to an instance via HTTP replication."""
  79. host: StrictStr
  80. port: StrictInt
  81. tls: StrictBool = False
  82. def scheme(self) -> str:
  83. """Hardcode a retrievable scheme based on self.tls"""
  84. return "https" if self.tls else "http"
  85. def netloc(self) -> str:
  86. """Nicely format the network location data"""
  87. return f"{self.host}:{self.port}"
  88. class InstanceUnixLocationConfig(ConfigModel):
  89. """The socket file to talk to an instance via HTTP replication."""
  90. path: StrictStr
  91. def scheme(self) -> str:
  92. """Hardcode a retrievable scheme"""
  93. return "unix"
  94. def netloc(self) -> str:
  95. """Nicely format the address location data"""
  96. return f"{self.path}"
  97. InstanceLocationConfig = Union[InstanceTcpLocationConfig, InstanceUnixLocationConfig]
  98. @attr.s
  99. class WriterLocations:
  100. """Specifies the instances that write various streams.
  101. Attributes:
  102. events: The instances that write to the event and backfill streams.
  103. typing: The instances that write to the typing stream. Currently
  104. can only be a single instance.
  105. to_device: The instances that write to the to_device stream. Currently
  106. can only be a single instance.
  107. account_data: The instances that write to the account data streams. Currently
  108. can only be a single instance.
  109. receipts: The instances that write to the receipts stream. Currently
  110. can only be a single instance.
  111. presence: The instances that write to the presence stream. Currently
  112. can only be a single instance.
  113. """
  114. events: List[str] = attr.ib(
  115. default=["master"],
  116. converter=_instance_to_list_converter,
  117. )
  118. typing: List[str] = attr.ib(
  119. default=["master"],
  120. converter=_instance_to_list_converter,
  121. )
  122. to_device: List[str] = attr.ib(
  123. default=["master"],
  124. converter=_instance_to_list_converter,
  125. )
  126. account_data: List[str] = attr.ib(
  127. default=["master"],
  128. converter=_instance_to_list_converter,
  129. )
  130. receipts: List[str] = attr.ib(
  131. default=["master"],
  132. converter=_instance_to_list_converter,
  133. )
  134. presence: List[str] = attr.ib(
  135. default=["master"],
  136. converter=_instance_to_list_converter,
  137. )
  138. class WorkerConfig(Config):
  139. """The workers are processes run separately to the main synapse process.
  140. They have their own pid_file and listener configuration. They use the
  141. replication_url to talk to the main synapse process."""
  142. section = "worker"
  143. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  144. self.worker_app = config.get("worker_app")
  145. # Canonicalise worker_app so that master always has None
  146. if self.worker_app == "synapse.app.homeserver":
  147. self.worker_app = None
  148. self.worker_listeners = [
  149. parse_listener_def(i, x)
  150. for i, x in enumerate(config.get("worker_listeners", []))
  151. ]
  152. self.worker_daemonize = bool(config.get("worker_daemonize"))
  153. self.worker_pid_file = config.get("worker_pid_file")
  154. worker_log_config = config.get("worker_log_config")
  155. if worker_log_config is not None and not isinstance(worker_log_config, str):
  156. raise ConfigError("worker_log_config must be a string")
  157. self.worker_log_config = worker_log_config
  158. # The port on the main synapse for TCP replication
  159. if "worker_replication_port" in config:
  160. raise ConfigError(DIRECT_TCP_ERROR, ("worker_replication_port",))
  161. # The shared secret used for authentication when connecting to the main synapse.
  162. self.worker_replication_secret = config.get("worker_replication_secret", None)
  163. self.worker_name = config.get("worker_name", self.worker_app)
  164. self.instance_name = self.worker_name or MAIN_PROCESS_INSTANCE_NAME
  165. # FIXME: Remove this check after a suitable amount of time.
  166. self.worker_main_http_uri = config.get("worker_main_http_uri", None)
  167. if self.worker_main_http_uri is not None:
  168. logger.warning(
  169. "The config option worker_main_http_uri is unused since Synapse 1.73. "
  170. "It can be safely removed from your configuration."
  171. )
  172. # This option is really only here to support `--manhole` command line
  173. # argument.
  174. manhole = config.get("worker_manhole")
  175. if manhole:
  176. self.worker_listeners.append(
  177. TCPListenerConfig(
  178. port=manhole,
  179. bind_addresses=["127.0.0.1"],
  180. type="manhole",
  181. )
  182. )
  183. federation_sender_instances = self._worker_names_performing_this_duty(
  184. config,
  185. "send_federation",
  186. "synapse.app.federation_sender",
  187. "federation_sender_instances",
  188. )
  189. self.send_federation = self.instance_name in federation_sender_instances
  190. self.federation_shard_config = ShardedWorkerHandlingConfig(
  191. federation_sender_instances
  192. )
  193. # A map from instance name to host/port of their HTTP replication endpoint.
  194. # Check if the main process is declared. The main process itself doesn't need
  195. # this data as it would never have to talk to itself.
  196. instance_map: Dict[str, Any] = config.get("instance_map", {})
  197. if self.instance_name is not MAIN_PROCESS_INSTANCE_NAME:
  198. # TODO: The next 3 condition blocks can be deleted after some time has
  199. # passed and we're ready to stop checking for these settings.
  200. # The host used to connect to the main synapse
  201. main_host = config.get("worker_replication_host", None)
  202. if main_host:
  203. raise ConfigError(
  204. WORKER_REPLICATION_SETTING_DEPRECATED_MESSAGE
  205. % ("worker_replication_host", main_host)
  206. )
  207. # The port on the main synapse for HTTP replication endpoint
  208. main_port = config.get("worker_replication_http_port")
  209. if main_port:
  210. raise ConfigError(
  211. WORKER_REPLICATION_SETTING_DEPRECATED_MESSAGE
  212. % ("worker_replication_http_port", main_port)
  213. )
  214. # The tls mode on the main synapse for HTTP replication endpoint.
  215. # For backward compatibility this defaults to False.
  216. main_tls = config.get("worker_replication_http_tls", False)
  217. if main_tls:
  218. raise ConfigError(
  219. WORKER_REPLICATION_SETTING_DEPRECATED_MESSAGE
  220. % ("worker_replication_http_tls", main_tls)
  221. )
  222. # For now, accept 'main' in the instance_map, but the replication system
  223. # expects 'master', force that into being until it's changed later.
  224. if MAIN_PROCESS_INSTANCE_MAP_NAME in instance_map:
  225. instance_map[MAIN_PROCESS_INSTANCE_NAME] = instance_map[
  226. MAIN_PROCESS_INSTANCE_MAP_NAME
  227. ]
  228. del instance_map[MAIN_PROCESS_INSTANCE_MAP_NAME]
  229. else:
  230. # If we've gotten here, it means that the main process is not on the
  231. # instance_map.
  232. raise ConfigError(
  233. _MISSING_MAIN_PROCESS_INSTANCE_MAP_DATA
  234. % MAIN_PROCESS_INSTANCE_MAP_NAME
  235. )
  236. # type-ignore: the expression `Union[A, B]` is not a Type[Union[A, B]] currently
  237. self.instance_map: Dict[
  238. str, InstanceLocationConfig
  239. ] = parse_and_validate_mapping(
  240. instance_map, InstanceLocationConfig # type: ignore[arg-type]
  241. )
  242. # Map from type of streams to source, c.f. WriterLocations.
  243. writers = config.get("stream_writers") or {}
  244. self.writers = WriterLocations(**writers)
  245. # Check that the configured writers for events and typing also appears in
  246. # `instance_map`.
  247. for stream in (
  248. "events",
  249. "typing",
  250. "to_device",
  251. "account_data",
  252. "receipts",
  253. "presence",
  254. ):
  255. instances = _instance_to_list_converter(getattr(self.writers, stream))
  256. for instance in instances:
  257. if instance != "master" and instance not in self.instance_map:
  258. raise ConfigError(
  259. "Instance %r is configured to write %s but does not appear in `instance_map` config."
  260. % (instance, stream)
  261. )
  262. if len(self.writers.typing) != 1:
  263. raise ConfigError(
  264. "Must only specify one instance to handle `typing` messages."
  265. )
  266. if len(self.writers.to_device) != 1:
  267. raise ConfigError(
  268. "Must only specify one instance to handle `to_device` messages."
  269. )
  270. if len(self.writers.account_data) != 1:
  271. raise ConfigError(
  272. "Must only specify one instance to handle `account_data` messages."
  273. )
  274. if len(self.writers.receipts) != 1:
  275. raise ConfigError(
  276. "Must only specify one instance to handle `receipts` messages."
  277. )
  278. if len(self.writers.events) == 0:
  279. raise ConfigError("Must specify at least one instance to handle `events`.")
  280. if len(self.writers.presence) != 1:
  281. raise ConfigError(
  282. "Must only specify one instance to handle `presence` messages."
  283. )
  284. self.events_shard_config = RoutableShardedWorkerHandlingConfig(
  285. self.writers.events
  286. )
  287. # Handle sharded push
  288. pusher_instances = self._worker_names_performing_this_duty(
  289. config,
  290. "start_pushers",
  291. "synapse.app.pusher",
  292. "pusher_instances",
  293. )
  294. self.start_pushers = self.instance_name in pusher_instances
  295. self.pusher_shard_config = ShardedWorkerHandlingConfig(pusher_instances)
  296. # Whether this worker should run background tasks or not.
  297. #
  298. # As a note for developers, the background tasks guarded by this should
  299. # be able to run on only a single instance (meaning that they don't
  300. # depend on any in-memory state of a particular worker).
  301. #
  302. # No effort is made to ensure only a single instance of these tasks is
  303. # running.
  304. background_tasks_instance = config.get("run_background_tasks_on") or "master"
  305. self.run_background_tasks = (
  306. self.worker_name is None and background_tasks_instance == "master"
  307. ) or self.worker_name == background_tasks_instance
  308. self.should_notify_appservices = self._should_this_worker_perform_duty(
  309. config,
  310. legacy_master_option_name="notify_appservices",
  311. legacy_worker_app_name="synapse.app.appservice",
  312. new_option_name="notify_appservices_from_worker",
  313. )
  314. self.should_update_user_directory = self._should_this_worker_perform_duty(
  315. config,
  316. legacy_master_option_name="update_user_directory",
  317. legacy_worker_app_name="synapse.app.user_dir",
  318. new_option_name="update_user_directory_from_worker",
  319. )
  320. def _should_this_worker_perform_duty(
  321. self,
  322. config: Dict[str, Any],
  323. legacy_master_option_name: str,
  324. legacy_worker_app_name: str,
  325. new_option_name: str,
  326. ) -> bool:
  327. """
  328. Figures out whether this worker should perform a certain duty.
  329. This function is temporary and is only to deal with the complexity
  330. of allowing old, transitional and new configurations all at once.
  331. Contradictions between the legacy and new part of a transitional configuration
  332. will lead to a ConfigError.
  333. Parameters:
  334. config: The config dictionary
  335. legacy_master_option_name: The name of a legacy option, whose value is boolean,
  336. specifying whether it's the master that should handle a certain duty.
  337. e.g. "notify_appservices"
  338. legacy_worker_app_name: The name of a legacy Synapse worker application
  339. that would traditionally perform this duty.
  340. e.g. "synapse.app.appservice"
  341. new_option_name: The name of the new option, whose value is the name of a
  342. designated worker to perform the duty.
  343. e.g. "notify_appservices_from_worker"
  344. """
  345. # None means 'unspecified'; True means 'run here' and False means
  346. # 'don't run here'.
  347. new_option_should_run_here = None
  348. if new_option_name in config:
  349. designated_worker = config[new_option_name] or "master"
  350. new_option_should_run_here = (
  351. designated_worker == "master" and self.worker_name is None
  352. ) or designated_worker == self.worker_name
  353. legacy_option_should_run_here = None
  354. if legacy_master_option_name in config:
  355. run_on_master = bool(config[legacy_master_option_name])
  356. legacy_option_should_run_here = (
  357. self.worker_name is None and run_on_master
  358. ) or (self.worker_app == legacy_worker_app_name and not run_on_master)
  359. # Suggest using the new option instead.
  360. logger.warning(
  361. _DEPRECATED_WORKER_DUTY_OPTION_USED,
  362. legacy_master_option_name,
  363. new_option_name,
  364. )
  365. if self.worker_app == legacy_worker_app_name and config.get(
  366. legacy_master_option_name, True
  367. ):
  368. # As an extra bit of complication, we need to check that the
  369. # specialised worker is only used if the legacy config says the
  370. # master isn't performing the duties.
  371. raise ConfigError(
  372. f"Cannot use deprecated worker app type '{legacy_worker_app_name}' whilst deprecated option '{legacy_master_option_name}' is not set to false.\n"
  373. f"Consider setting `worker_app: synapse.app.generic_worker` and using the '{new_option_name}' option instead.\n"
  374. f"The '{new_option_name}' option replaces '{legacy_master_option_name}'."
  375. )
  376. if new_option_should_run_here is None and legacy_option_should_run_here is None:
  377. # Neither option specified; the fallback behaviour is to run on the main process
  378. return self.worker_name is None
  379. if (
  380. new_option_should_run_here is not None
  381. and legacy_option_should_run_here is not None
  382. ):
  383. # Both options specified; ensure they match!
  384. if new_option_should_run_here != legacy_option_should_run_here:
  385. update_worker_type = (
  386. " and set worker_app: synapse.app.generic_worker"
  387. if self.worker_app == legacy_worker_app_name
  388. else ""
  389. )
  390. # If the values conflict, we suggest the admin removes the legacy option
  391. # for simplicity.
  392. raise ConfigError(
  393. f"Conflicting configuration options: {legacy_master_option_name} (legacy), {new_option_name} (new).\n"
  394. f"Suggestion: remove {legacy_master_option_name}{update_worker_type}.\n"
  395. )
  396. # We've already validated that these aren't conflicting; now just see if
  397. # either is True.
  398. # (By this point, these are either the same value or only one is not None.)
  399. return bool(new_option_should_run_here or legacy_option_should_run_here)
  400. def _worker_names_performing_this_duty(
  401. self,
  402. config: Dict[str, Any],
  403. legacy_option_name: str,
  404. legacy_app_name: str,
  405. modern_instance_list_name: str,
  406. ) -> List[str]:
  407. """
  408. Retrieves the names of the workers handling a given duty, by either legacy
  409. option or instance list.
  410. There are two ways of configuring which instances handle a given duty, e.g.
  411. for configuring pushers:
  412. 1. The old way where "start_pushers" is set to false and running a
  413. `synapse.app.pusher'` worker app.
  414. 2. Specifying the workers sending federation in `pusher_instances`.
  415. Args:
  416. config: settings read from yaml.
  417. legacy_option_name: the old way of enabling options. e.g. 'start_pushers'
  418. legacy_app_name: The historical app name. e.g. 'synapse.app.pusher'
  419. modern_instance_list_name: the string name of the new instance_list. e.g.
  420. 'pusher_instances'
  421. Returns:
  422. A list of worker instance names handling the given duty.
  423. """
  424. legacy_option = config.get(legacy_option_name, True)
  425. worker_instances = config.get(modern_instance_list_name)
  426. if worker_instances is None:
  427. # Default to an empty list, which means "another, unknown, worker is
  428. # responsible for it".
  429. worker_instances = []
  430. # If no worker instances are set we check if the legacy option
  431. # is set, which means use the main process.
  432. if legacy_option:
  433. worker_instances = ["master"]
  434. if self.worker_app == legacy_app_name:
  435. if legacy_option:
  436. # If we're using `legacy_app_name`, and not using
  437. # `modern_instance_list_name`, then we should have
  438. # explicitly set `legacy_option_name` to false.
  439. raise ConfigError(
  440. f"The '{legacy_option_name}' config option must be disabled in "
  441. "the main synapse process before they can be run in a separate "
  442. "worker.\n"
  443. f"Please add `{legacy_option_name}: false` to the main config.\n",
  444. )
  445. worker_instances = [self.worker_name]
  446. return worker_instances
  447. def read_arguments(self, args: argparse.Namespace) -> None:
  448. # We support a bunch of command line arguments that override options in
  449. # the config. A lot of these options have a worker_* prefix when running
  450. # on workers so we also have to override them when command line options
  451. # are specified.
  452. if args.daemonize is not None:
  453. self.worker_daemonize = args.daemonize
  454. if args.manhole is not None:
  455. self.worker_manhole = args.worker_manhole