Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

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