_base.py 29 KB

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