Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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