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.
 
 
 
 
 
 

927 lines
31 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2017-2018 New Vector Ltd
  3. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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 argparse
  17. import errno
  18. import os
  19. from collections import OrderedDict
  20. from hashlib import sha256
  21. from textwrap import dedent
  22. from typing import Any, Iterable, List, MutableMapping, Optional, Union
  23. import attr
  24. import jinja2
  25. import pkg_resources
  26. import yaml
  27. from synapse.util.templates import _create_mxc_to_http_filter, _format_ts_filter
  28. class ConfigError(Exception):
  29. """Represents a problem parsing the configuration
  30. Args:
  31. msg: A textual description of the error.
  32. path: Where appropriate, an indication of where in the configuration
  33. the problem lies.
  34. """
  35. def __init__(self, msg: str, path: Optional[Iterable[str]] = None):
  36. self.msg = msg
  37. self.path = path
  38. # We split these messages out to allow packages to override with package
  39. # specific instructions.
  40. MISSING_REPORT_STATS_CONFIG_INSTRUCTIONS = """\
  41. Please opt in or out of reporting anonymized homeserver usage statistics, by
  42. setting the `report_stats` key in your config file to either True or False.
  43. """
  44. MISSING_REPORT_STATS_SPIEL = """\
  45. We would really appreciate it if you could help our project out by reporting
  46. anonymized usage statistics from your homeserver. Only very basic aggregate
  47. data (e.g. number of users) will be reported, but it helps us to track the
  48. growth of the Matrix community, and helps us to make Matrix a success, as well
  49. as to convince other networks that they should peer with us.
  50. Thank you.
  51. """
  52. MISSING_SERVER_NAME = """\
  53. Missing mandatory `server_name` config option.
  54. """
  55. CONFIG_FILE_HEADER = """\
  56. # Configuration file for Synapse.
  57. #
  58. # This is a YAML file: see [1] for a quick introduction. Note in particular
  59. # that *indentation is important*: all the elements of a list or dictionary
  60. # should have the same indentation.
  61. #
  62. # [1] https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
  63. """
  64. def path_exists(file_path):
  65. """Check if a file exists
  66. Unlike os.path.exists, this throws an exception if there is an error
  67. checking if the file exists (for example, if there is a perms error on
  68. the parent dir).
  69. Returns:
  70. bool: True if the file exists; False if not.
  71. """
  72. try:
  73. os.stat(file_path)
  74. return True
  75. except OSError as e:
  76. if e.errno != errno.ENOENT:
  77. raise e
  78. return False
  79. class Config:
  80. """
  81. A configuration section, containing configuration keys and values.
  82. Attributes:
  83. section (str): The section title of this config object, such as
  84. "tls" or "logger". This is used to refer to it on the root
  85. logger (for example, `config.tls.some_option`). Must be
  86. defined in subclasses.
  87. """
  88. section = None
  89. def __init__(self, root_config=None):
  90. self.root = root_config
  91. # Get the path to the default Synapse template directory
  92. self.default_template_dir = pkg_resources.resource_filename(
  93. "synapse", "res/templates"
  94. )
  95. def __getattr__(self, item: str) -> Any:
  96. """
  97. Try and fetch a configuration option that does not exist on this class.
  98. This is so that existing configs that rely on `self.value`, where value
  99. is actually from a different config section, continue to work.
  100. """
  101. if item in ["generate_config_section", "read_config"]:
  102. raise AttributeError(item)
  103. if self.root is None:
  104. raise AttributeError(item)
  105. else:
  106. return self.root._get_unclassed_config(self.section, item)
  107. @staticmethod
  108. def parse_size(value):
  109. if isinstance(value, int):
  110. return value
  111. sizes = {"K": 1024, "M": 1024 * 1024}
  112. size = 1
  113. suffix = value[-1]
  114. if suffix in sizes:
  115. value = value[:-1]
  116. size = sizes[suffix]
  117. return int(value) * size
  118. @staticmethod
  119. def parse_duration(value: Union[str, int]) -> int:
  120. """Convert a duration as a string or integer to a number of milliseconds.
  121. If an integer is provided it is treated as milliseconds and is unchanged.
  122. String durations can have a suffix of 's', 'm', 'h', 'd', 'w', or 'y'.
  123. No suffix is treated as milliseconds.
  124. Args:
  125. value: The duration to parse.
  126. Returns:
  127. The number of milliseconds in the duration.
  128. """
  129. if isinstance(value, int):
  130. return value
  131. second = 1000
  132. minute = 60 * second
  133. hour = 60 * minute
  134. day = 24 * hour
  135. week = 7 * day
  136. year = 365 * day
  137. sizes = {"s": second, "m": minute, "h": hour, "d": day, "w": week, "y": year}
  138. size = 1
  139. suffix = value[-1]
  140. if suffix in sizes:
  141. value = value[:-1]
  142. size = sizes[suffix]
  143. return int(value) * size
  144. @staticmethod
  145. def abspath(file_path):
  146. return os.path.abspath(file_path) if file_path else file_path
  147. @classmethod
  148. def path_exists(cls, file_path):
  149. return path_exists(file_path)
  150. @classmethod
  151. def check_file(cls, file_path, config_name):
  152. if file_path is None:
  153. raise ConfigError("Missing config for %s." % (config_name,))
  154. try:
  155. os.stat(file_path)
  156. except OSError as e:
  157. raise ConfigError(
  158. "Error accessing file '%s' (config for %s): %s"
  159. % (file_path, config_name, e.strerror)
  160. )
  161. return cls.abspath(file_path)
  162. @classmethod
  163. def ensure_directory(cls, dir_path):
  164. dir_path = cls.abspath(dir_path)
  165. try:
  166. os.makedirs(dir_path)
  167. except OSError as e:
  168. if e.errno != errno.EEXIST:
  169. raise
  170. if not os.path.isdir(dir_path):
  171. raise ConfigError("%s is not a directory" % (dir_path,))
  172. return dir_path
  173. @classmethod
  174. def read_file(cls, file_path, config_name):
  175. """Deprecated: call read_file directly"""
  176. return read_file(file_path, (config_name,))
  177. def read_template(self, filename: str) -> jinja2.Template:
  178. """Load a template file from disk.
  179. This function will attempt to load the given template from the default Synapse
  180. template directory.
  181. Files read are treated as Jinja templates. The templates is not rendered yet
  182. and has autoescape enabled.
  183. Args:
  184. filename: A template filename to read.
  185. Raises:
  186. ConfigError: if the file's path is incorrect or otherwise cannot be read.
  187. Returns:
  188. A jinja2 template.
  189. """
  190. return self.read_templates([filename])[0]
  191. def read_templates(
  192. self,
  193. filenames: List[str],
  194. custom_template_directory: Optional[str] = None,
  195. ) -> List[jinja2.Template]:
  196. """Load a list of template files from disk using the given variables.
  197. This function will attempt to load the given templates from the default Synapse
  198. template directory. If `custom_template_directory` is supplied, that directory
  199. is tried first.
  200. Files read are treated as Jinja templates. The templates are not rendered yet
  201. and have autoescape enabled.
  202. Args:
  203. filenames: A list of template filenames to read.
  204. custom_template_directory: A directory to try to look for the templates
  205. before using the default Synapse template directory instead.
  206. Raises:
  207. ConfigError: if the file's path is incorrect or otherwise cannot be read.
  208. Returns:
  209. A list of jinja2 templates.
  210. """
  211. search_directories = [self.default_template_dir]
  212. # The loader will first look in the custom template directory (if specified) for the
  213. # given filename. If it doesn't find it, it will use the default template dir instead
  214. if custom_template_directory:
  215. # Check that the given template directory exists
  216. if not self.path_exists(custom_template_directory):
  217. raise ConfigError(
  218. "Configured template directory does not exist: %s"
  219. % (custom_template_directory,)
  220. )
  221. # Search the custom template directory as well
  222. search_directories.insert(0, custom_template_directory)
  223. # TODO: switch to synapse.util.templates.build_jinja_env
  224. loader = jinja2.FileSystemLoader(search_directories)
  225. env = jinja2.Environment(
  226. loader=loader,
  227. autoescape=jinja2.select_autoescape(),
  228. )
  229. # Update the environment with our custom filters
  230. env.filters.update(
  231. {
  232. "format_ts": _format_ts_filter,
  233. "mxc_to_http": _create_mxc_to_http_filter(self.public_baseurl),
  234. }
  235. )
  236. # Load the templates
  237. return [env.get_template(filename) for filename in filenames]
  238. class RootConfig:
  239. """
  240. Holder of an application's configuration.
  241. What configuration this object holds is defined by `config_classes`, a list
  242. of Config classes that will be instantiated and given the contents of a
  243. configuration file to read. They can then be accessed on this class by their
  244. section name, defined in the Config or dynamically set to be the name of the
  245. class, lower-cased and with "Config" removed.
  246. """
  247. config_classes = []
  248. def __init__(self):
  249. self._configs = OrderedDict()
  250. for config_class in self.config_classes:
  251. if config_class.section is None:
  252. raise ValueError("%r requires a section name" % (config_class,))
  253. try:
  254. conf = config_class(self)
  255. except Exception as e:
  256. raise Exception("Failed making %s: %r" % (config_class.section, e))
  257. self._configs[config_class.section] = conf
  258. def __getattr__(self, item: str) -> Any:
  259. """
  260. Redirect lookups on this object either to config objects, or values on
  261. config objects, so that `config.tls.blah` works, as well as legacy uses
  262. of things like `config.server_name`. It will first look up the config
  263. section name, and then values on those config classes.
  264. """
  265. if item in self._configs.keys():
  266. return self._configs[item]
  267. return self._get_unclassed_config(None, item)
  268. def _get_unclassed_config(self, asking_section: Optional[str], item: str):
  269. """
  270. Fetch a config value from one of the instantiated config classes that
  271. has not been fetched directly.
  272. Args:
  273. asking_section: If this check is coming from a Config child, which
  274. one? This section will not be asked if it has the value.
  275. item: The configuration value key.
  276. Raises:
  277. AttributeError if no config classes have the config key. The body
  278. will contain what sections were checked.
  279. """
  280. for key, val in self._configs.items():
  281. if key == asking_section:
  282. continue
  283. if item in dir(val):
  284. return getattr(val, item)
  285. raise AttributeError(item, "not found in %s" % (list(self._configs.keys()),))
  286. def invoke_all(self, func_name: str, *args, **kwargs) -> MutableMapping[str, Any]:
  287. """
  288. Invoke a function on all instantiated config objects this RootConfig is
  289. configured to use.
  290. Args:
  291. func_name: Name of function to invoke
  292. *args
  293. **kwargs
  294. Returns:
  295. ordered dictionary of config section name and the result of the
  296. function from it.
  297. """
  298. res = OrderedDict()
  299. for name, config in self._configs.items():
  300. if hasattr(config, func_name):
  301. res[name] = getattr(config, func_name)(*args, **kwargs)
  302. return res
  303. @classmethod
  304. def invoke_all_static(cls, func_name: str, *args, **kwargs):
  305. """
  306. Invoke a static function on config objects this RootConfig is
  307. configured to use.
  308. Args:
  309. func_name: Name of function to invoke
  310. *args
  311. **kwargs
  312. Returns:
  313. ordered dictionary of config section name and the result of the
  314. function from it.
  315. """
  316. for config in cls.config_classes:
  317. if hasattr(config, func_name):
  318. getattr(config, func_name)(*args, **kwargs)
  319. def generate_config(
  320. self,
  321. config_dir_path,
  322. data_dir_path,
  323. server_name,
  324. generate_secrets=False,
  325. report_stats=None,
  326. open_private_ports=False,
  327. listeners=None,
  328. tls_certificate_path=None,
  329. tls_private_key_path=None,
  330. acme_domain=None,
  331. ):
  332. """
  333. Build a default configuration file
  334. This is used when the user explicitly asks us to generate a config file
  335. (eg with --generate_config).
  336. Args:
  337. config_dir_path (str): The path where the config files are kept. Used to
  338. create filenames for things like the log config and the signing key.
  339. data_dir_path (str): The path where the data files are kept. Used to create
  340. filenames for things like the database and media store.
  341. server_name (str): The server name. Used to initialise the server_name
  342. config param, but also used in the names of some of the config files.
  343. generate_secrets (bool): True if we should generate new secrets for things
  344. like the macaroon_secret_key. If False, these parameters will be left
  345. unset.
  346. report_stats (bool|None): Initial setting for the report_stats setting.
  347. If None, report_stats will be left unset.
  348. open_private_ports (bool): True to leave private ports (such as the non-TLS
  349. HTTP listener) open to the internet.
  350. listeners (list(dict)|None): A list of descriptions of the listeners
  351. synapse should start with each of which specifies a port (str), a list of
  352. resources (list(str)), tls (bool) and type (str). For example:
  353. [{
  354. "port": 8448,
  355. "resources": [{"names": ["federation"]}],
  356. "tls": True,
  357. "type": "http",
  358. },
  359. {
  360. "port": 443,
  361. "resources": [{"names": ["client"]}],
  362. "tls": False,
  363. "type": "http",
  364. }],
  365. database (str|None): The database type to configure, either `psycog2`
  366. or `sqlite3`.
  367. tls_certificate_path (str|None): The path to the tls certificate.
  368. tls_private_key_path (str|None): The path to the tls private key.
  369. acme_domain (str|None): The domain acme will try to validate. If
  370. specified acme will be enabled.
  371. Returns:
  372. str: the yaml config file
  373. """
  374. return CONFIG_FILE_HEADER + "\n\n".join(
  375. dedent(conf)
  376. for conf in self.invoke_all(
  377. "generate_config_section",
  378. config_dir_path=config_dir_path,
  379. data_dir_path=data_dir_path,
  380. server_name=server_name,
  381. generate_secrets=generate_secrets,
  382. report_stats=report_stats,
  383. open_private_ports=open_private_ports,
  384. listeners=listeners,
  385. tls_certificate_path=tls_certificate_path,
  386. tls_private_key_path=tls_private_key_path,
  387. acme_domain=acme_domain,
  388. ).values()
  389. )
  390. @classmethod
  391. def load_config(cls, description, argv):
  392. """Parse the commandline and config files
  393. Doesn't support config-file-generation: used by the worker apps.
  394. Returns: Config object.
  395. """
  396. config_parser = argparse.ArgumentParser(description=description)
  397. cls.add_arguments_to_parser(config_parser)
  398. obj, _ = cls.load_config_with_parser(config_parser, argv)
  399. return obj
  400. @classmethod
  401. def add_arguments_to_parser(cls, config_parser):
  402. """Adds all the config flags to an ArgumentParser.
  403. Doesn't support config-file-generation: used by the worker apps.
  404. Used for workers where we want to add extra flags/subcommands.
  405. Args:
  406. config_parser (ArgumentParser): App description
  407. """
  408. config_parser.add_argument(
  409. "-c",
  410. "--config-path",
  411. action="append",
  412. metavar="CONFIG_FILE",
  413. help="Specify config file. Can be given multiple times and"
  414. " may specify directories containing *.yaml files.",
  415. )
  416. config_parser.add_argument(
  417. "--keys-directory",
  418. metavar="DIRECTORY",
  419. help="Where files such as certs and signing keys are stored when"
  420. " their location is not given explicitly in the config."
  421. " Defaults to the directory containing the last config file",
  422. )
  423. cls.invoke_all_static("add_arguments", config_parser)
  424. @classmethod
  425. def load_config_with_parser(cls, parser, argv):
  426. """Parse the commandline and config files with the given parser
  427. Doesn't support config-file-generation: used by the worker apps.
  428. Used for workers where we want to add extra flags/subcommands.
  429. Args:
  430. parser (ArgumentParser)
  431. argv (list[str])
  432. Returns:
  433. tuple[HomeServerConfig, argparse.Namespace]: Returns the parsed
  434. config object and the parsed argparse.Namespace object from
  435. `parser.parse_args(..)`
  436. """
  437. obj = cls()
  438. config_args = parser.parse_args(argv)
  439. config_files = find_config_files(search_paths=config_args.config_path)
  440. if not config_files:
  441. parser.error("Must supply a config file.")
  442. if config_args.keys_directory:
  443. config_dir_path = config_args.keys_directory
  444. else:
  445. config_dir_path = os.path.dirname(config_files[-1])
  446. config_dir_path = os.path.abspath(config_dir_path)
  447. data_dir_path = os.getcwd()
  448. config_dict = read_config_files(config_files)
  449. obj.parse_config_dict(
  450. config_dict, config_dir_path=config_dir_path, data_dir_path=data_dir_path
  451. )
  452. obj.invoke_all("read_arguments", config_args)
  453. return obj, config_args
  454. @classmethod
  455. def load_or_generate_config(cls, description, argv):
  456. """Parse the commandline and config files
  457. Supports generation of config files, so is used for the main homeserver app.
  458. Returns: Config object, or None if --generate-config or --generate-keys was set
  459. """
  460. parser = argparse.ArgumentParser(description=description)
  461. parser.add_argument(
  462. "-c",
  463. "--config-path",
  464. action="append",
  465. metavar="CONFIG_FILE",
  466. help="Specify config file. Can be given multiple times and"
  467. " may specify directories containing *.yaml files.",
  468. )
  469. generate_group = parser.add_argument_group("Config generation")
  470. generate_group.add_argument(
  471. "--generate-config",
  472. action="store_true",
  473. help="Generate a config file, then exit.",
  474. )
  475. generate_group.add_argument(
  476. "--generate-missing-configs",
  477. "--generate-keys",
  478. action="store_true",
  479. help="Generate any missing additional config files, then exit.",
  480. )
  481. generate_group.add_argument(
  482. "-H", "--server-name", help="The server name to generate a config file for."
  483. )
  484. generate_group.add_argument(
  485. "--report-stats",
  486. action="store",
  487. help="Whether the generated config reports anonymized usage statistics.",
  488. choices=["yes", "no"],
  489. )
  490. generate_group.add_argument(
  491. "--config-directory",
  492. "--keys-directory",
  493. metavar="DIRECTORY",
  494. help=(
  495. "Specify where additional config files such as signing keys and log"
  496. " config should be stored. Defaults to the same directory as the last"
  497. " config file."
  498. ),
  499. )
  500. generate_group.add_argument(
  501. "--data-directory",
  502. metavar="DIRECTORY",
  503. help=(
  504. "Specify where data such as the media store and database file should be"
  505. " stored. Defaults to the current working directory."
  506. ),
  507. )
  508. generate_group.add_argument(
  509. "--open-private-ports",
  510. action="store_true",
  511. help=(
  512. "Leave private ports (such as the non-TLS HTTP listener) open to the"
  513. " internet. Do not use this unless you know what you are doing."
  514. ),
  515. )
  516. cls.invoke_all_static("add_arguments", parser)
  517. config_args = parser.parse_args(argv)
  518. config_files = find_config_files(search_paths=config_args.config_path)
  519. if not config_files:
  520. parser.error(
  521. "Must supply a config file.\nA config file can be automatically"
  522. ' generated using "--generate-config -H SERVER_NAME'
  523. ' -c CONFIG-FILE"'
  524. )
  525. if config_args.config_directory:
  526. config_dir_path = config_args.config_directory
  527. else:
  528. config_dir_path = os.path.dirname(config_files[-1])
  529. config_dir_path = os.path.abspath(config_dir_path)
  530. data_dir_path = os.getcwd()
  531. generate_missing_configs = config_args.generate_missing_configs
  532. obj = cls()
  533. if config_args.generate_config:
  534. if config_args.report_stats is None:
  535. parser.error(
  536. "Please specify either --report-stats=yes or --report-stats=no\n\n"
  537. + MISSING_REPORT_STATS_SPIEL
  538. )
  539. (config_path,) = config_files
  540. if not path_exists(config_path):
  541. print("Generating config file %s" % (config_path,))
  542. if config_args.data_directory:
  543. data_dir_path = config_args.data_directory
  544. else:
  545. data_dir_path = os.getcwd()
  546. data_dir_path = os.path.abspath(data_dir_path)
  547. server_name = config_args.server_name
  548. if not server_name:
  549. raise ConfigError(
  550. "Must specify a server_name to a generate config for."
  551. " Pass -H server.name."
  552. )
  553. config_str = obj.generate_config(
  554. config_dir_path=config_dir_path,
  555. data_dir_path=data_dir_path,
  556. server_name=server_name,
  557. report_stats=(config_args.report_stats == "yes"),
  558. generate_secrets=True,
  559. open_private_ports=config_args.open_private_ports,
  560. )
  561. if not path_exists(config_dir_path):
  562. os.makedirs(config_dir_path)
  563. with open(config_path, "w") as config_file:
  564. config_file.write(config_str)
  565. config_file.write("\n\n# vim:ft=yaml")
  566. config_dict = yaml.safe_load(config_str)
  567. obj.generate_missing_files(config_dict, config_dir_path)
  568. print(
  569. (
  570. "A config file has been generated in %r for server name"
  571. " %r. Please review this file and customise it"
  572. " to your needs."
  573. )
  574. % (config_path, server_name)
  575. )
  576. return
  577. else:
  578. print(
  579. (
  580. "Config file %r already exists. Generating any missing config"
  581. " files."
  582. )
  583. % (config_path,)
  584. )
  585. generate_missing_configs = True
  586. config_dict = read_config_files(config_files)
  587. if generate_missing_configs:
  588. obj.generate_missing_files(config_dict, config_dir_path)
  589. return None
  590. obj.parse_config_dict(
  591. config_dict, config_dir_path=config_dir_path, data_dir_path=data_dir_path
  592. )
  593. obj.invoke_all("read_arguments", config_args)
  594. return obj
  595. def parse_config_dict(self, config_dict, config_dir_path=None, data_dir_path=None):
  596. """Read the information from the config dict into this Config object.
  597. Args:
  598. config_dict (dict): Configuration data, as read from the yaml
  599. config_dir_path (str): The path where the config files are kept. Used to
  600. create filenames for things like the log config and the signing key.
  601. data_dir_path (str): The path where the data files are kept. Used to create
  602. filenames for things like the database and media store.
  603. """
  604. self.invoke_all(
  605. "read_config",
  606. config_dict,
  607. config_dir_path=config_dir_path,
  608. data_dir_path=data_dir_path,
  609. )
  610. def generate_missing_files(self, config_dict, config_dir_path):
  611. self.invoke_all("generate_files", config_dict, config_dir_path)
  612. def read_config_files(config_files):
  613. """Read the config files into a dict
  614. Args:
  615. config_files (iterable[str]): A list of the config files to read
  616. Returns: dict
  617. """
  618. specified_config = {}
  619. for config_file in config_files:
  620. with open(config_file) as file_stream:
  621. yaml_config = yaml.safe_load(file_stream)
  622. if not isinstance(yaml_config, dict):
  623. err = "File %r is empty or doesn't parse into a key-value map. IGNORING."
  624. print(err % (config_file,))
  625. continue
  626. specified_config.update(yaml_config)
  627. if "server_name" not in specified_config:
  628. raise ConfigError(MISSING_SERVER_NAME)
  629. if "report_stats" not in specified_config:
  630. raise ConfigError(
  631. MISSING_REPORT_STATS_CONFIG_INSTRUCTIONS + "\n" + MISSING_REPORT_STATS_SPIEL
  632. )
  633. return specified_config
  634. def find_config_files(search_paths):
  635. """Finds config files using a list of search paths. If a path is a file
  636. then that file path is added to the list. If a search path is a directory
  637. then all the "*.yaml" files in that directory are added to the list in
  638. sorted order.
  639. Args:
  640. search_paths(list(str)): A list of paths to search.
  641. Returns:
  642. list(str): A list of file paths.
  643. """
  644. config_files = []
  645. if search_paths:
  646. for config_path in search_paths:
  647. if os.path.isdir(config_path):
  648. # We accept specifying directories as config paths, we search
  649. # inside that directory for all files matching *.yaml, and then
  650. # we apply them in *sorted* order.
  651. files = []
  652. for entry in os.listdir(config_path):
  653. entry_path = os.path.join(config_path, entry)
  654. if not os.path.isfile(entry_path):
  655. err = "Found subdirectory in config directory: %r. IGNORING."
  656. print(err % (entry_path,))
  657. continue
  658. if not entry.endswith(".yaml"):
  659. err = (
  660. "Found file in config directory that does not end in "
  661. "'.yaml': %r. IGNORING."
  662. )
  663. print(err % (entry_path,))
  664. continue
  665. files.append(entry_path)
  666. config_files.extend(sorted(files))
  667. else:
  668. config_files.append(config_path)
  669. return config_files
  670. @attr.s
  671. class ShardedWorkerHandlingConfig:
  672. """Algorithm for choosing which instance is responsible for handling some
  673. sharded work.
  674. For example, the federation senders use this to determine which instances
  675. handles sending stuff to a given destination (which is used as the `key`
  676. below).
  677. """
  678. instances = attr.ib(type=List[str])
  679. def should_handle(self, instance_name: str, key: str) -> bool:
  680. """Whether this instance is responsible for handling the given key."""
  681. # If no instances are defined we assume some other worker is handling
  682. # this.
  683. if not self.instances:
  684. return False
  685. return self._get_instance(key) == instance_name
  686. def _get_instance(self, key: str) -> str:
  687. """Get the instance responsible for handling the given key.
  688. Note: For federation sending and pushers the config for which instance
  689. is sending is known only to the sender instance, so we don't expose this
  690. method by default.
  691. """
  692. if not self.instances:
  693. raise Exception("Unknown worker")
  694. if len(self.instances) == 1:
  695. return self.instances[0]
  696. # We shard by taking the hash, modulo it by the number of instances and
  697. # then checking whether this instance matches the instance at that
  698. # index.
  699. #
  700. # (Technically this introduces some bias and is not entirely uniform,
  701. # but since the hash is so large the bias is ridiculously small).
  702. dest_hash = sha256(key.encode("utf8")).digest()
  703. dest_int = int.from_bytes(dest_hash, byteorder="little")
  704. remainder = dest_int % (len(self.instances))
  705. return self.instances[remainder]
  706. @attr.s
  707. class RoutableShardedWorkerHandlingConfig(ShardedWorkerHandlingConfig):
  708. """A version of `ShardedWorkerHandlingConfig` that is used for config
  709. options where all instances know which instances are responsible for the
  710. sharded work.
  711. """
  712. def __attrs_post_init__(self):
  713. # We require that `self.instances` is non-empty.
  714. if not self.instances:
  715. raise Exception("Got empty list of instances for shard config")
  716. def get_instance(self, key: str) -> str:
  717. """Get the instance responsible for handling the given key."""
  718. return self._get_instance(key)
  719. def read_file(file_path: Any, config_path: Iterable[str]) -> str:
  720. """Check the given file exists, and read it into a string
  721. If it does not, emit an error indicating the problem
  722. Args:
  723. file_path: the file to be read
  724. config_path: where in the configuration file_path came from, so that a useful
  725. error can be emitted if it does not exist.
  726. Returns:
  727. content of the file.
  728. Raises:
  729. ConfigError if there is a problem reading the file.
  730. """
  731. if not isinstance(file_path, str):
  732. raise ConfigError("%r is not a string", config_path)
  733. try:
  734. os.stat(file_path)
  735. with open(file_path) as file_stream:
  736. return file_stream.read()
  737. except OSError as e:
  738. raise ConfigError("Error accessing file %r" % (file_path,), config_path) from e
  739. __all__ = [
  740. "Config",
  741. "RootConfig",
  742. "ShardedWorkerHandlingConfig",
  743. "RoutableShardedWorkerHandlingConfig",
  744. "read_file",
  745. ]