workers.py 18 KB

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