_base.py 31 KB

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