_base.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import argparse
  16. import errno
  17. import os
  18. from textwrap import dedent
  19. from six import integer_types
  20. import yaml
  21. class ConfigError(Exception):
  22. pass
  23. # We split these messages out to allow packages to override with package
  24. # specific instructions.
  25. MISSING_REPORT_STATS_CONFIG_INSTRUCTIONS = """\
  26. Please opt in or out of reporting anonymized homeserver usage statistics, by
  27. setting the `report_stats` key in your config file to either True or False.
  28. """
  29. MISSING_REPORT_STATS_SPIEL = """\
  30. We would really appreciate it if you could help our project out by reporting
  31. anonymized usage statistics from your homeserver. Only very basic aggregate
  32. data (e.g. number of users) will be reported, but it helps us to track the
  33. growth of the Matrix community, and helps us to make Matrix a success, as well
  34. as to convince other networks that they should peer with us.
  35. Thank you.
  36. """
  37. MISSING_SERVER_NAME = """\
  38. Missing mandatory `server_name` config option.
  39. """
  40. class Config(object):
  41. @staticmethod
  42. def parse_size(value):
  43. if isinstance(value, integer_types):
  44. return value
  45. sizes = {"K": 1024, "M": 1024 * 1024}
  46. size = 1
  47. suffix = value[-1]
  48. if suffix in sizes:
  49. value = value[:-1]
  50. size = sizes[suffix]
  51. return int(value) * size
  52. @staticmethod
  53. def parse_duration(value):
  54. if isinstance(value, integer_types):
  55. return value
  56. second = 1000
  57. minute = 60 * second
  58. hour = 60 * minute
  59. day = 24 * hour
  60. week = 7 * day
  61. year = 365 * day
  62. sizes = {"s": second, "m": minute, "h": hour, "d": day, "w": week, "y": year}
  63. size = 1
  64. suffix = value[-1]
  65. if suffix in sizes:
  66. value = value[:-1]
  67. size = sizes[suffix]
  68. return int(value) * size
  69. @staticmethod
  70. def abspath(file_path):
  71. return os.path.abspath(file_path) if file_path else file_path
  72. @classmethod
  73. def path_exists(cls, file_path):
  74. """Check if a file exists
  75. Unlike os.path.exists, this throws an exception if there is an error
  76. checking if the file exists (for example, if there is a perms error on
  77. the parent dir).
  78. Returns:
  79. bool: True if the file exists; False if not.
  80. """
  81. try:
  82. os.stat(file_path)
  83. return True
  84. except OSError as e:
  85. if e.errno != errno.ENOENT:
  86. raise e
  87. return False
  88. @classmethod
  89. def check_file(cls, file_path, config_name):
  90. if file_path is None:
  91. raise ConfigError("Missing config for %s." % (config_name,))
  92. try:
  93. os.stat(file_path)
  94. except OSError as e:
  95. raise ConfigError(
  96. "Error accessing file '%s' (config for %s): %s"
  97. % (file_path, config_name, e.strerror)
  98. )
  99. return cls.abspath(file_path)
  100. @classmethod
  101. def ensure_directory(cls, dir_path):
  102. dir_path = cls.abspath(dir_path)
  103. try:
  104. os.makedirs(dir_path)
  105. except OSError as e:
  106. if e.errno != errno.EEXIST:
  107. raise
  108. if not os.path.isdir(dir_path):
  109. raise ConfigError("%s is not a directory" % (dir_path,))
  110. return dir_path
  111. @classmethod
  112. def read_file(cls, file_path, config_name):
  113. cls.check_file(file_path, config_name)
  114. with open(file_path) as file_stream:
  115. return file_stream.read()
  116. @staticmethod
  117. def read_config_file(file_path):
  118. with open(file_path) as file_stream:
  119. return yaml.load(file_stream)
  120. def invoke_all(self, name, *args, **kargs):
  121. results = []
  122. for cls in type(self).mro():
  123. if name in cls.__dict__:
  124. results.append(getattr(cls, name)(self, *args, **kargs))
  125. return results
  126. def generate_config(
  127. self,
  128. config_dir_path,
  129. data_dir_path,
  130. server_name,
  131. generate_secrets=False,
  132. report_stats=None,
  133. ):
  134. """Build a default configuration file
  135. This is used both when the user explicitly asks us to generate a config file
  136. (eg with --generate_config), and before loading the config at runtime (to give
  137. a base which the config files override)
  138. Args:
  139. config_dir_path (str): The path where the config files are kept. Used to
  140. create filenames for things like the log config and the signing key.
  141. data_dir_path (str): The path where the data files are kept. Used to create
  142. filenames for things like the database and media store.
  143. server_name (str): The server name. Used to initialise the server_name
  144. config param, but also used in the names of some of the config files.
  145. generate_secrets (bool): True if we should generate new secrets for things
  146. like the macaroon_secret_key. If False, these parameters will be left
  147. unset.
  148. report_stats (bool|None): Initial setting for the report_stats setting.
  149. If None, report_stats will be left unset.
  150. Returns:
  151. str: the yaml config file
  152. """
  153. default_config = "# vim:ft=yaml\n"
  154. default_config += "\n\n".join(
  155. dedent(conf)
  156. for conf in self.invoke_all(
  157. "default_config",
  158. config_dir_path=config_dir_path,
  159. data_dir_path=data_dir_path,
  160. server_name=server_name,
  161. generate_secrets=generate_secrets,
  162. report_stats=report_stats,
  163. )
  164. )
  165. return default_config
  166. @classmethod
  167. def load_config(cls, description, argv):
  168. config_parser = argparse.ArgumentParser(description=description)
  169. config_parser.add_argument(
  170. "-c",
  171. "--config-path",
  172. action="append",
  173. metavar="CONFIG_FILE",
  174. help="Specify config file. Can be given multiple times and"
  175. " may specify directories containing *.yaml files.",
  176. )
  177. config_parser.add_argument(
  178. "--keys-directory",
  179. metavar="DIRECTORY",
  180. help="Where files such as certs and signing keys are stored when"
  181. " their location is given explicitly in the config."
  182. " Defaults to the directory containing the last config file",
  183. )
  184. config_args = config_parser.parse_args(argv)
  185. config_files = find_config_files(search_paths=config_args.config_path)
  186. obj = cls()
  187. obj.read_config_files(
  188. config_files, keys_directory=config_args.keys_directory, generate_keys=False
  189. )
  190. return obj
  191. @classmethod
  192. def load_or_generate_config(cls, description, argv):
  193. config_parser = argparse.ArgumentParser(add_help=False)
  194. config_parser.add_argument(
  195. "-c",
  196. "--config-path",
  197. action="append",
  198. metavar="CONFIG_FILE",
  199. help="Specify config file. Can be given multiple times and"
  200. " may specify directories containing *.yaml files.",
  201. )
  202. config_parser.add_argument(
  203. "--generate-config",
  204. action="store_true",
  205. help="Generate a config file for the server name",
  206. )
  207. config_parser.add_argument(
  208. "--report-stats",
  209. action="store",
  210. help="Whether the generated config reports anonymized usage statistics",
  211. choices=["yes", "no"],
  212. )
  213. config_parser.add_argument(
  214. "--generate-keys",
  215. action="store_true",
  216. help="Generate any missing key files then exit",
  217. )
  218. config_parser.add_argument(
  219. "--keys-directory",
  220. metavar="DIRECTORY",
  221. help="Used with 'generate-*' options to specify where files such as"
  222. " certs and signing keys should be stored in, unless explicitly"
  223. " specified in the config.",
  224. )
  225. config_parser.add_argument(
  226. "-H", "--server-name", help="The server name to generate a config file for"
  227. )
  228. config_args, remaining_args = config_parser.parse_known_args(argv)
  229. config_files = find_config_files(search_paths=config_args.config_path)
  230. generate_keys = config_args.generate_keys
  231. obj = cls()
  232. if config_args.generate_config:
  233. if config_args.report_stats is None:
  234. config_parser.error(
  235. "Please specify either --report-stats=yes or --report-stats=no\n\n"
  236. + MISSING_REPORT_STATS_SPIEL
  237. )
  238. if not config_files:
  239. config_parser.error(
  240. "Must supply a config file.\nA config file can be automatically"
  241. " generated using \"--generate-config -H SERVER_NAME"
  242. " -c CONFIG-FILE\""
  243. )
  244. (config_path,) = config_files
  245. if not cls.path_exists(config_path):
  246. if config_args.keys_directory:
  247. config_dir_path = config_args.keys_directory
  248. else:
  249. config_dir_path = os.path.dirname(config_path)
  250. config_dir_path = os.path.abspath(config_dir_path)
  251. server_name = config_args.server_name
  252. if not server_name:
  253. raise ConfigError(
  254. "Must specify a server_name to a generate config for."
  255. " Pass -H server.name."
  256. )
  257. if not cls.path_exists(config_dir_path):
  258. os.makedirs(config_dir_path)
  259. with open(config_path, "w") as config_file:
  260. config_str = obj.generate_config(
  261. config_dir_path=config_dir_path,
  262. data_dir_path=os.getcwd(),
  263. server_name=server_name,
  264. report_stats=(config_args.report_stats == "yes"),
  265. generate_secrets=True,
  266. )
  267. config = yaml.load(config_str)
  268. obj.invoke_all("generate_files", config)
  269. config_file.write(config_str)
  270. print(
  271. (
  272. "A config file has been generated in %r for server name"
  273. " %r with corresponding SSL keys and self-signed"
  274. " certificates. Please review this file and customise it"
  275. " to your needs."
  276. )
  277. % (config_path, server_name)
  278. )
  279. print(
  280. "If this server name is incorrect, you will need to"
  281. " regenerate the SSL certificates"
  282. )
  283. return
  284. else:
  285. print(
  286. (
  287. "Config file %r already exists. Generating any missing key"
  288. " files."
  289. )
  290. % (config_path,)
  291. )
  292. generate_keys = True
  293. parser = argparse.ArgumentParser(
  294. parents=[config_parser],
  295. description=description,
  296. formatter_class=argparse.RawDescriptionHelpFormatter,
  297. )
  298. obj.invoke_all("add_arguments", parser)
  299. args = parser.parse_args(remaining_args)
  300. if not config_files:
  301. config_parser.error(
  302. "Must supply a config file.\nA config file can be automatically"
  303. " generated using \"--generate-config -H SERVER_NAME"
  304. " -c CONFIG-FILE\""
  305. )
  306. obj.read_config_files(
  307. config_files,
  308. keys_directory=config_args.keys_directory,
  309. generate_keys=generate_keys,
  310. )
  311. if generate_keys:
  312. return None
  313. obj.invoke_all("read_arguments", args)
  314. return obj
  315. def read_config_files(self, config_files, keys_directory=None, generate_keys=False):
  316. if not keys_directory:
  317. keys_directory = os.path.dirname(config_files[-1])
  318. config_dir_path = os.path.abspath(keys_directory)
  319. specified_config = {}
  320. for config_file in config_files:
  321. yaml_config = self.read_config_file(config_file)
  322. specified_config.update(yaml_config)
  323. if "server_name" not in specified_config:
  324. raise ConfigError(MISSING_SERVER_NAME)
  325. server_name = specified_config["server_name"]
  326. config_string = self.generate_config(
  327. config_dir_path=config_dir_path,
  328. data_dir_path=os.getcwd(),
  329. server_name=server_name,
  330. generate_secrets=False,
  331. )
  332. config = yaml.load(config_string)
  333. config.pop("log_config")
  334. config.update(specified_config)
  335. if "report_stats" not in config:
  336. raise ConfigError(
  337. MISSING_REPORT_STATS_CONFIG_INSTRUCTIONS
  338. + "\n"
  339. + MISSING_REPORT_STATS_SPIEL
  340. )
  341. if generate_keys:
  342. self.invoke_all("generate_files", config)
  343. return
  344. self.invoke_all("read_config", config)
  345. def find_config_files(search_paths):
  346. """Finds config files using a list of search paths. If a path is a file
  347. then that file path is added to the list. If a search path is a directory
  348. then all the "*.yaml" files in that directory are added to the list in
  349. sorted order.
  350. Args:
  351. search_paths(list(str)): A list of paths to search.
  352. Returns:
  353. list(str): A list of file paths.
  354. """
  355. config_files = []
  356. if search_paths:
  357. for config_path in search_paths:
  358. if os.path.isdir(config_path):
  359. # We accept specifying directories as config paths, we search
  360. # inside that directory for all files matching *.yaml, and then
  361. # we apply them in *sorted* order.
  362. files = []
  363. for entry in os.listdir(config_path):
  364. entry_path = os.path.join(config_path, entry)
  365. if not os.path.isfile(entry_path):
  366. err = "Found subdirectory in config directory: %r. IGNORING."
  367. print(err % (entry_path,))
  368. continue
  369. if not entry.endswith(".yaml"):
  370. err = (
  371. "Found file in config directory that does not end in "
  372. "'.yaml': %r. IGNORING."
  373. )
  374. print(err % (entry_path,))
  375. continue
  376. files.append(entry_path)
  377. config_files.extend(sorted(files))
  378. else:
  379. config_files.append(config_path)
  380. return config_files