_base.py 30 KB

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