_base.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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(
  92. "Missing config for %s."
  93. % (config_name,)
  94. )
  95. try:
  96. os.stat(file_path)
  97. except OSError as e:
  98. raise ConfigError(
  99. "Error accessing file '%s' (config for %s): %s"
  100. % (file_path, config_name, e.strerror)
  101. )
  102. return cls.abspath(file_path)
  103. @classmethod
  104. def ensure_directory(cls, dir_path):
  105. dir_path = cls.abspath(dir_path)
  106. try:
  107. os.makedirs(dir_path)
  108. except OSError as e:
  109. if e.errno != errno.EEXIST:
  110. raise
  111. if not os.path.isdir(dir_path):
  112. raise ConfigError(
  113. "%s is not a directory" % (dir_path,)
  114. )
  115. return dir_path
  116. @classmethod
  117. def read_file(cls, file_path, config_name):
  118. cls.check_file(file_path, config_name)
  119. with open(file_path) as file_stream:
  120. return file_stream.read()
  121. @staticmethod
  122. def default_path(name):
  123. return os.path.abspath(os.path.join(os.path.curdir, name))
  124. @staticmethod
  125. def read_config_file(file_path):
  126. with open(file_path) as file_stream:
  127. return yaml.load(file_stream)
  128. def invoke_all(self, name, *args, **kargs):
  129. results = []
  130. for cls in type(self).mro():
  131. if name in cls.__dict__:
  132. results.append(getattr(cls, name)(self, *args, **kargs))
  133. return results
  134. def generate_config(
  135. self,
  136. config_dir_path,
  137. server_name,
  138. is_generating_file,
  139. report_stats=None,
  140. ):
  141. default_config = "# vim:ft=yaml\n"
  142. default_config += "\n\n".join(dedent(conf) for conf in self.invoke_all(
  143. "default_config",
  144. config_dir_path=config_dir_path,
  145. server_name=server_name,
  146. is_generating_file=is_generating_file,
  147. report_stats=report_stats,
  148. ))
  149. config = yaml.load(default_config)
  150. return default_config, config
  151. @classmethod
  152. def load_config(cls, description, argv):
  153. config_parser = argparse.ArgumentParser(
  154. description=description,
  155. )
  156. config_parser.add_argument(
  157. "-c", "--config-path",
  158. action="append",
  159. metavar="CONFIG_FILE",
  160. help="Specify config file. Can be given multiple times and"
  161. " may specify directories containing *.yaml files."
  162. )
  163. config_parser.add_argument(
  164. "--keys-directory",
  165. metavar="DIRECTORY",
  166. help="Where files such as certs and signing keys are stored when"
  167. " their location is given explicitly in the config."
  168. " Defaults to the directory containing the last config file",
  169. )
  170. config_args = config_parser.parse_args(argv)
  171. config_files = find_config_files(search_paths=config_args.config_path)
  172. obj = cls()
  173. obj.read_config_files(
  174. config_files,
  175. keys_directory=config_args.keys_directory,
  176. generate_keys=False,
  177. )
  178. return obj
  179. @classmethod
  180. def load_or_generate_config(cls, description, argv):
  181. config_parser = argparse.ArgumentParser(add_help=False)
  182. config_parser.add_argument(
  183. "-c", "--config-path",
  184. action="append",
  185. metavar="CONFIG_FILE",
  186. help="Specify config file. Can be given multiple times and"
  187. " may specify directories containing *.yaml files."
  188. )
  189. config_parser.add_argument(
  190. "--generate-config",
  191. action="store_true",
  192. help="Generate a config file for the server name"
  193. )
  194. config_parser.add_argument(
  195. "--report-stats",
  196. action="store",
  197. help="Whether the generated config reports anonymized usage statistics",
  198. choices=["yes", "no"]
  199. )
  200. config_parser.add_argument(
  201. "--generate-keys",
  202. action="store_true",
  203. help="Generate any missing key files then exit"
  204. )
  205. config_parser.add_argument(
  206. "--keys-directory",
  207. metavar="DIRECTORY",
  208. help="Used with 'generate-*' options to specify where files such as"
  209. " certs and signing keys should be stored in, unless explicitly"
  210. " specified in the config."
  211. )
  212. config_parser.add_argument(
  213. "-H", "--server-name",
  214. help="The server name to generate a config file for"
  215. )
  216. config_args, remaining_args = config_parser.parse_known_args(argv)
  217. config_files = find_config_files(search_paths=config_args.config_path)
  218. generate_keys = config_args.generate_keys
  219. obj = cls()
  220. if config_args.generate_config:
  221. if config_args.report_stats is None:
  222. config_parser.error(
  223. "Please specify either --report-stats=yes or --report-stats=no\n\n" +
  224. MISSING_REPORT_STATS_SPIEL
  225. )
  226. if not config_files:
  227. config_parser.error(
  228. "Must supply a config file.\nA config file can be automatically"
  229. " generated using \"--generate-config -H SERVER_NAME"
  230. " -c CONFIG-FILE\""
  231. )
  232. (config_path,) = config_files
  233. if not cls.path_exists(config_path):
  234. if config_args.keys_directory:
  235. config_dir_path = config_args.keys_directory
  236. else:
  237. config_dir_path = os.path.dirname(config_path)
  238. config_dir_path = os.path.abspath(config_dir_path)
  239. server_name = config_args.server_name
  240. if not server_name:
  241. raise ConfigError(
  242. "Must specify a server_name to a generate config for."
  243. " Pass -H server.name."
  244. )
  245. if not cls.path_exists(config_dir_path):
  246. os.makedirs(config_dir_path)
  247. with open(config_path, "w") as config_file:
  248. config_str, config = obj.generate_config(
  249. config_dir_path=config_dir_path,
  250. server_name=server_name,
  251. report_stats=(config_args.report_stats == "yes"),
  252. is_generating_file=True
  253. )
  254. obj.invoke_all("generate_files", config)
  255. config_file.write(config_str)
  256. print((
  257. "A config file has been generated in %r for server name"
  258. " %r with corresponding SSL keys and self-signed"
  259. " certificates. Please review this file and customise it"
  260. " to your needs."
  261. ) % (config_path, server_name))
  262. print(
  263. "If this server name is incorrect, you will need to"
  264. " regenerate the SSL certificates"
  265. )
  266. return
  267. else:
  268. print((
  269. "Config file %r already exists. Generating any missing key"
  270. " files."
  271. ) % (config_path,))
  272. generate_keys = True
  273. parser = argparse.ArgumentParser(
  274. parents=[config_parser],
  275. description=description,
  276. formatter_class=argparse.RawDescriptionHelpFormatter,
  277. )
  278. obj.invoke_all("add_arguments", parser)
  279. args = parser.parse_args(remaining_args)
  280. if not config_files:
  281. config_parser.error(
  282. "Must supply a config file.\nA config file can be automatically"
  283. " generated using \"--generate-config -H SERVER_NAME"
  284. " -c CONFIG-FILE\""
  285. )
  286. obj.read_config_files(
  287. config_files,
  288. keys_directory=config_args.keys_directory,
  289. generate_keys=generate_keys,
  290. )
  291. if generate_keys:
  292. return None
  293. obj.invoke_all("read_arguments", args)
  294. return obj
  295. def read_config_files(self, config_files, keys_directory=None,
  296. generate_keys=False):
  297. if not keys_directory:
  298. keys_directory = os.path.dirname(config_files[-1])
  299. config_dir_path = os.path.abspath(keys_directory)
  300. specified_config = {}
  301. for config_file in config_files:
  302. yaml_config = self.read_config_file(config_file)
  303. specified_config.update(yaml_config)
  304. if "server_name" not in specified_config:
  305. raise ConfigError(MISSING_SERVER_NAME)
  306. server_name = specified_config["server_name"]
  307. _, config = self.generate_config(
  308. config_dir_path=config_dir_path,
  309. server_name=server_name,
  310. is_generating_file=False,
  311. )
  312. config.pop("log_config")
  313. config.update(specified_config)
  314. if "report_stats" not in config:
  315. raise ConfigError(
  316. MISSING_REPORT_STATS_CONFIG_INSTRUCTIONS + "\n" +
  317. MISSING_REPORT_STATS_SPIEL
  318. )
  319. if generate_keys:
  320. self.invoke_all("generate_files", config)
  321. return
  322. self.invoke_all("read_config", config)
  323. def find_config_files(search_paths):
  324. """Finds config files using a list of search paths. If a path is a file
  325. then that file path is added to the list. If a search path is a directory
  326. then all the "*.yaml" files in that directory are added to the list in
  327. sorted order.
  328. Args:
  329. search_paths(list(str)): A list of paths to search.
  330. Returns:
  331. list(str): A list of file paths.
  332. """
  333. config_files = []
  334. if search_paths:
  335. for config_path in search_paths:
  336. if os.path.isdir(config_path):
  337. # We accept specifying directories as config paths, we search
  338. # inside that directory for all files matching *.yaml, and then
  339. # we apply them in *sorted* order.
  340. files = []
  341. for entry in os.listdir(config_path):
  342. entry_path = os.path.join(config_path, entry)
  343. if not os.path.isfile(entry_path):
  344. print (
  345. "Found subdirectory in config directory: %r. IGNORING."
  346. ) % (entry_path, )
  347. continue
  348. if not entry.endswith(".yaml"):
  349. print (
  350. "Found file in config directory that does not"
  351. " end in '.yaml': %r. IGNORING."
  352. ) % (entry_path, )
  353. continue
  354. files.append(entry_path)
  355. config_files.extend(sorted(files))
  356. else:
  357. config_files.append(config_path)
  358. return config_files