_base.py 24 KB

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