_base.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. import yaml
  19. from textwrap import dedent
  20. class ConfigError(Exception):
  21. pass
  22. # We split these messages out to allow packages to override with package
  23. # specific instructions.
  24. MISSING_REPORT_STATS_CONFIG_INSTRUCTIONS = """\
  25. Please opt in or out of reporting anonymized homeserver usage statistics, by
  26. setting the `report_stats` key in your config file to either True or False.
  27. """
  28. MISSING_REPORT_STATS_SPIEL = """\
  29. We would really appreciate it if you could help our project out by reporting
  30. anonymized usage statistics from your homeserver. Only very basic aggregate
  31. data (e.g. number of users) will be reported, but it helps us to track the
  32. growth of the Matrix community, and helps us to make Matrix a success, as well
  33. as to convince other networks that they should peer with us.
  34. Thank you.
  35. """
  36. MISSING_SERVER_NAME = """\
  37. Missing mandatory `server_name` config option.
  38. """
  39. class Config(object):
  40. @staticmethod
  41. def parse_size(value):
  42. if isinstance(value, int) or isinstance(value, long):
  43. return value
  44. sizes = {"K": 1024, "M": 1024 * 1024}
  45. size = 1
  46. suffix = value[-1]
  47. if suffix in sizes:
  48. value = value[:-1]
  49. size = sizes[suffix]
  50. return int(value) * size
  51. @staticmethod
  52. def parse_duration(value):
  53. if isinstance(value, int) or isinstance(value, long):
  54. return value
  55. second = 1000
  56. hour = 60 * 60 * second
  57. day = 24 * hour
  58. week = 7 * day
  59. year = 365 * day
  60. sizes = {"s": second, "h": hour, "d": day, "w": week, "y": year}
  61. size = 1
  62. suffix = value[-1]
  63. if suffix in sizes:
  64. value = value[:-1]
  65. size = sizes[suffix]
  66. return int(value) * size
  67. @staticmethod
  68. def abspath(file_path):
  69. return os.path.abspath(file_path) if file_path else file_path
  70. @classmethod
  71. def check_file(cls, file_path, config_name):
  72. if file_path is None:
  73. raise ConfigError(
  74. "Missing config for %s."
  75. " You must specify a path for the config file. You can "
  76. "do this with the -c or --config-path option. "
  77. "Adding --generate-config along with --server-name "
  78. "<server name> will generate a config file at the given path."
  79. % (config_name,)
  80. )
  81. if not os.path.exists(file_path):
  82. raise ConfigError(
  83. "File %s config for %s doesn't exist."
  84. " Try running again with --generate-config"
  85. % (file_path, config_name,)
  86. )
  87. return cls.abspath(file_path)
  88. @classmethod
  89. def ensure_directory(cls, dir_path):
  90. dir_path = cls.abspath(dir_path)
  91. try:
  92. os.makedirs(dir_path)
  93. except OSError as e:
  94. if e.errno != errno.EEXIST:
  95. raise
  96. if not os.path.isdir(dir_path):
  97. raise ConfigError(
  98. "%s is not a directory" % (dir_path,)
  99. )
  100. return dir_path
  101. @classmethod
  102. def read_file(cls, file_path, config_name):
  103. cls.check_file(file_path, config_name)
  104. with open(file_path) as file_stream:
  105. return file_stream.read()
  106. @staticmethod
  107. def default_path(name):
  108. return os.path.abspath(os.path.join(os.path.curdir, name))
  109. @staticmethod
  110. def read_config_file(file_path):
  111. with open(file_path) as file_stream:
  112. return yaml.load(file_stream)
  113. def invoke_all(self, name, *args, **kargs):
  114. results = []
  115. for cls in type(self).mro():
  116. if name in cls.__dict__:
  117. results.append(getattr(cls, name)(self, *args, **kargs))
  118. return results
  119. def generate_config(
  120. self,
  121. config_dir_path,
  122. server_name,
  123. is_generating_file,
  124. report_stats=None,
  125. ):
  126. default_config = "# vim:ft=yaml\n"
  127. default_config += "\n\n".join(dedent(conf) for conf in self.invoke_all(
  128. "default_config",
  129. config_dir_path=config_dir_path,
  130. server_name=server_name,
  131. is_generating_file=is_generating_file,
  132. report_stats=report_stats,
  133. ))
  134. config = yaml.load(default_config)
  135. return default_config, config
  136. @classmethod
  137. def load_config(cls, description, argv, generate_section=None):
  138. obj = cls()
  139. config_parser = argparse.ArgumentParser(add_help=False)
  140. config_parser.add_argument(
  141. "-c", "--config-path",
  142. action="append",
  143. metavar="CONFIG_FILE",
  144. help="Specify config file. Can be given multiple times and"
  145. " may specify directories containing *.yaml files."
  146. )
  147. config_parser.add_argument(
  148. "--generate-config",
  149. action="store_true",
  150. help="Generate a config file for the server name"
  151. )
  152. config_parser.add_argument(
  153. "--report-stats",
  154. action="store",
  155. help="Stuff",
  156. choices=["yes", "no"]
  157. )
  158. config_parser.add_argument(
  159. "--generate-keys",
  160. action="store_true",
  161. help="Generate any missing key files then exit"
  162. )
  163. config_parser.add_argument(
  164. "--keys-directory",
  165. metavar="DIRECTORY",
  166. help="Used with 'generate-*' options to specify where files such as"
  167. " certs and signing keys should be stored in, unless explicitly"
  168. " specified in the config."
  169. )
  170. config_parser.add_argument(
  171. "-H", "--server-name",
  172. help="The server name to generate a config file for"
  173. )
  174. config_args, remaining_args = config_parser.parse_known_args(argv)
  175. generate_keys = config_args.generate_keys
  176. config_files = []
  177. if config_args.config_path:
  178. for config_path in config_args.config_path:
  179. if os.path.isdir(config_path):
  180. # We accept specifying directories as config paths, we search
  181. # inside that directory for all files matching *.yaml, and then
  182. # we apply them in *sorted* order.
  183. files = []
  184. for entry in os.listdir(config_path):
  185. entry_path = os.path.join(config_path, entry)
  186. if not os.path.isfile(entry_path):
  187. print (
  188. "Found subdirectory in config directory: %r. IGNORING."
  189. ) % (entry_path, )
  190. continue
  191. if not entry.endswith(".yaml"):
  192. print (
  193. "Found file in config directory that does not"
  194. " end in '.yaml': %r. IGNORING."
  195. ) % (entry_path, )
  196. continue
  197. files.append(entry_path)
  198. config_files.extend(sorted(files))
  199. else:
  200. config_files.append(config_path)
  201. if config_args.generate_config:
  202. if config_args.report_stats is None:
  203. config_parser.error(
  204. "Please specify either --report-stats=yes or --report-stats=no\n\n" +
  205. MISSING_REPORT_STATS_SPIEL
  206. )
  207. if not config_files:
  208. config_parser.error(
  209. "Must supply a config file.\nA config file can be automatically"
  210. " generated using \"--generate-config -H SERVER_NAME"
  211. " -c CONFIG-FILE\""
  212. )
  213. (config_path,) = config_files
  214. if not os.path.exists(config_path):
  215. if config_args.keys_directory:
  216. config_dir_path = config_args.keys_directory
  217. else:
  218. config_dir_path = os.path.dirname(config_path)
  219. config_dir_path = os.path.abspath(config_dir_path)
  220. server_name = config_args.server_name
  221. if not server_name:
  222. raise ConfigError(
  223. "Must specify a server_name to a generate config for."
  224. " Pass -H server.name."
  225. )
  226. if not os.path.exists(config_dir_path):
  227. os.makedirs(config_dir_path)
  228. with open(config_path, "wb") as config_file:
  229. config_bytes, config = obj.generate_config(
  230. config_dir_path=config_dir_path,
  231. server_name=server_name,
  232. report_stats=(config_args.report_stats == "yes"),
  233. is_generating_file=True
  234. )
  235. obj.invoke_all("generate_files", config)
  236. config_file.write(config_bytes)
  237. print (
  238. "A config file has been generated in %r for server name"
  239. " %r with corresponding SSL keys and self-signed"
  240. " certificates. Please review this file and customise it"
  241. " to your needs."
  242. ) % (config_path, server_name)
  243. print (
  244. "If this server name is incorrect, you will need to"
  245. " regenerate the SSL certificates"
  246. )
  247. return
  248. else:
  249. print (
  250. "Config file %r already exists. Generating any missing key"
  251. " files."
  252. ) % (config_path,)
  253. generate_keys = True
  254. parser = argparse.ArgumentParser(
  255. parents=[config_parser],
  256. description=description,
  257. formatter_class=argparse.RawDescriptionHelpFormatter,
  258. )
  259. obj.invoke_all("add_arguments", parser)
  260. args = parser.parse_args(remaining_args)
  261. if not config_files:
  262. config_parser.error(
  263. "Must supply a config file.\nA config file can be automatically"
  264. " generated using \"--generate-config -H SERVER_NAME"
  265. " -c CONFIG-FILE\""
  266. )
  267. if config_args.keys_directory:
  268. config_dir_path = config_args.keys_directory
  269. else:
  270. config_dir_path = os.path.dirname(config_args.config_path[-1])
  271. config_dir_path = os.path.abspath(config_dir_path)
  272. specified_config = {}
  273. for config_file in config_files:
  274. yaml_config = cls.read_config_file(config_file)
  275. specified_config.update(yaml_config)
  276. if "server_name" not in specified_config:
  277. raise ConfigError(MISSING_SERVER_NAME)
  278. server_name = specified_config["server_name"]
  279. _, config = obj.generate_config(
  280. config_dir_path=config_dir_path,
  281. server_name=server_name,
  282. is_generating_file=False,
  283. )
  284. config.pop("log_config")
  285. config.update(specified_config)
  286. if "report_stats" not in config:
  287. raise ConfigError(
  288. MISSING_REPORT_STATS_CONFIG_INSTRUCTIONS + "\n" +
  289. MISSING_REPORT_STATS_SPIEL
  290. )
  291. if generate_keys:
  292. obj.invoke_all("generate_files", config)
  293. return
  294. obj.invoke_all("read_config", config)
  295. obj.invoke_all("read_arguments", args)
  296. return obj