prepare_database.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 - 2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  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 fnmatch
  17. import imp
  18. import logging
  19. import os
  20. import re
  21. logger = logging.getLogger(__name__)
  22. # Remember to update this number every time a change is made to database
  23. # schema files, so the users will be informed on server restarts.
  24. SCHEMA_VERSION = 53
  25. dir_path = os.path.abspath(os.path.dirname(__file__))
  26. class PrepareDatabaseException(Exception):
  27. pass
  28. class UpgradeDatabaseException(PrepareDatabaseException):
  29. pass
  30. def prepare_database(db_conn, database_engine, config):
  31. """Prepares a database for usage. Will either create all necessary tables
  32. or upgrade from an older schema version.
  33. If `config` is None then prepare_database will assert that no upgrade is
  34. necessary, *or* will create a fresh database if the database is empty.
  35. Args:
  36. db_conn:
  37. database_engine:
  38. config (synapse.config.homeserver.HomeServerConfig|None):
  39. application config, or None if we are connecting to an existing
  40. database which we expect to be configured already
  41. """
  42. try:
  43. cur = db_conn.cursor()
  44. version_info = _get_or_create_schema_state(cur, database_engine)
  45. if version_info:
  46. user_version, delta_files, upgraded = version_info
  47. if config is None:
  48. if user_version != SCHEMA_VERSION:
  49. # If we don't pass in a config file then we are expecting to
  50. # have already upgraded the DB.
  51. raise UpgradeDatabaseException("Database needs to be upgraded")
  52. else:
  53. _upgrade_existing_database(
  54. cur, user_version, delta_files, upgraded, database_engine, config
  55. )
  56. else:
  57. _setup_new_database(cur, database_engine)
  58. # check if any of our configured dynamic modules want a database
  59. if config is not None:
  60. _apply_module_schemas(cur, database_engine, config)
  61. cur.close()
  62. db_conn.commit()
  63. except Exception:
  64. db_conn.rollback()
  65. raise
  66. def _setup_new_database(cur, database_engine):
  67. """Sets up the database by finding a base set of "full schemas" and then
  68. applying any necessary deltas.
  69. The "full_schemas" directory has subdirectories named after versions. This
  70. function searches for the highest version less than or equal to
  71. `SCHEMA_VERSION` and executes all .sql files in that directory.
  72. The function will then apply all deltas for all versions after the base
  73. version.
  74. Example directory structure:
  75. schema/
  76. delta/
  77. ...
  78. full_schemas/
  79. 3/
  80. test.sql
  81. ...
  82. 11/
  83. foo.sql
  84. bar.sql
  85. ...
  86. In the example foo.sql and bar.sql would be run, and then any delta files
  87. for versions strictly greater than 11.
  88. """
  89. current_dir = os.path.join(dir_path, "schema", "full_schemas")
  90. directory_entries = os.listdir(current_dir)
  91. valid_dirs = []
  92. pattern = re.compile(r"^\d+(\.sql)?$")
  93. for filename in directory_entries:
  94. match = pattern.match(filename)
  95. abs_path = os.path.join(current_dir, filename)
  96. if match and os.path.isdir(abs_path):
  97. ver = int(match.group(0))
  98. if ver <= SCHEMA_VERSION:
  99. valid_dirs.append((ver, abs_path))
  100. else:
  101. logger.warn("Unexpected entry in 'full_schemas': %s", filename)
  102. if not valid_dirs:
  103. raise PrepareDatabaseException(
  104. "Could not find a suitable base set of full schemas"
  105. )
  106. max_current_ver, sql_dir = max(valid_dirs, key=lambda x: x[0])
  107. logger.debug("Initialising schema v%d", max_current_ver)
  108. directory_entries = os.listdir(sql_dir)
  109. for filename in fnmatch.filter(directory_entries, "*.sql"):
  110. sql_loc = os.path.join(sql_dir, filename)
  111. logger.debug("Applying schema %s", sql_loc)
  112. executescript(cur, sql_loc)
  113. cur.execute(
  114. database_engine.convert_param_style(
  115. "INSERT INTO schema_version (version, upgraded)"
  116. " VALUES (?,?)"
  117. ),
  118. (max_current_ver, False,)
  119. )
  120. _upgrade_existing_database(
  121. cur,
  122. current_version=max_current_ver,
  123. applied_delta_files=[],
  124. upgraded=False,
  125. database_engine=database_engine,
  126. config=None,
  127. is_empty=True,
  128. )
  129. def _upgrade_existing_database(cur, current_version, applied_delta_files,
  130. upgraded, database_engine, config, is_empty=False):
  131. """Upgrades an existing database.
  132. Delta files can either be SQL stored in *.sql files, or python modules
  133. in *.py.
  134. There can be multiple delta files per version. Synapse will keep track of
  135. which delta files have been applied, and will apply any that haven't been
  136. even if there has been no version bump. This is useful for development
  137. where orthogonal schema changes may happen on separate branches.
  138. Different delta files for the same version *must* be orthogonal and give
  139. the same result when applied in any order. No guarantees are made on the
  140. order of execution of these scripts.
  141. This is a no-op of current_version == SCHEMA_VERSION.
  142. Example directory structure:
  143. schema/
  144. delta/
  145. 11/
  146. foo.sql
  147. ...
  148. 12/
  149. foo.sql
  150. bar.py
  151. ...
  152. full_schemas/
  153. ...
  154. In the example, if current_version is 11, then foo.sql will be run if and
  155. only if `upgraded` is True. Then `foo.sql` and `bar.py` would be run in
  156. some arbitrary order.
  157. Args:
  158. cur (Cursor)
  159. current_version (int): The current version of the schema.
  160. applied_delta_files (list): A list of deltas that have already been
  161. applied.
  162. upgraded (bool): Whether the current version was generated by having
  163. applied deltas or from full schema file. If `True` the function
  164. will never apply delta files for the given `current_version`, since
  165. the current_version wasn't generated by applying those delta files.
  166. """
  167. if current_version > SCHEMA_VERSION:
  168. raise ValueError(
  169. "Cannot use this database as it is too " +
  170. "new for the server to understand"
  171. )
  172. start_ver = current_version
  173. if not upgraded:
  174. start_ver += 1
  175. logger.debug("applied_delta_files: %s", applied_delta_files)
  176. for v in range(start_ver, SCHEMA_VERSION + 1):
  177. logger.info("Upgrading schema to v%d", v)
  178. delta_dir = os.path.join(dir_path, "schema", "delta", str(v))
  179. try:
  180. directory_entries = os.listdir(delta_dir)
  181. except OSError:
  182. logger.exception("Could not open delta dir for version %d", v)
  183. raise UpgradeDatabaseException(
  184. "Could not open delta dir for version %d" % (v,)
  185. )
  186. directory_entries.sort()
  187. for file_name in directory_entries:
  188. relative_path = os.path.join(str(v), file_name)
  189. logger.debug("Found file: %s", relative_path)
  190. if relative_path in applied_delta_files:
  191. continue
  192. absolute_path = os.path.join(
  193. dir_path, "schema", "delta", relative_path,
  194. )
  195. root_name, ext = os.path.splitext(file_name)
  196. if ext == ".py":
  197. # This is a python upgrade module. We need to import into some
  198. # package and then execute its `run_upgrade` function.
  199. module_name = "synapse.storage.v%d_%s" % (
  200. v, root_name
  201. )
  202. with open(absolute_path) as python_file:
  203. module = imp.load_source(
  204. module_name, absolute_path, python_file
  205. )
  206. logger.info("Running script %s", relative_path)
  207. module.run_create(cur, database_engine)
  208. if not is_empty:
  209. module.run_upgrade(cur, database_engine, config=config)
  210. elif ext == ".pyc" or file_name == "__pycache__":
  211. # Sometimes .pyc files turn up anyway even though we've
  212. # disabled their generation; e.g. from distribution package
  213. # installers. Silently skip it
  214. pass
  215. elif ext == ".sql":
  216. # A plain old .sql file, just read and execute it
  217. logger.info("Applying schema %s", relative_path)
  218. executescript(cur, absolute_path)
  219. else:
  220. # Not a valid delta file.
  221. logger.warn(
  222. "Found directory entry that did not end in .py or"
  223. " .sql: %s",
  224. relative_path,
  225. )
  226. continue
  227. # Mark as done.
  228. cur.execute(
  229. database_engine.convert_param_style(
  230. "INSERT INTO applied_schema_deltas (version, file)"
  231. " VALUES (?,?)",
  232. ),
  233. (v, relative_path)
  234. )
  235. cur.execute("DELETE FROM schema_version")
  236. cur.execute(
  237. database_engine.convert_param_style(
  238. "INSERT INTO schema_version (version, upgraded)"
  239. " VALUES (?,?)",
  240. ),
  241. (v, True)
  242. )
  243. def _apply_module_schemas(txn, database_engine, config):
  244. """Apply the module schemas for the dynamic modules, if any
  245. Args:
  246. cur: database cursor
  247. database_engine: synapse database engine class
  248. config (synapse.config.homeserver.HomeServerConfig):
  249. application config
  250. """
  251. for (mod, _config) in config.password_providers:
  252. if not hasattr(mod, 'get_db_schema_files'):
  253. continue
  254. modname = ".".join((mod.__module__, mod.__name__))
  255. _apply_module_schema_files(
  256. txn, database_engine, modname, mod.get_db_schema_files(),
  257. )
  258. def _apply_module_schema_files(cur, database_engine, modname, names_and_streams):
  259. """Apply the module schemas for a single module
  260. Args:
  261. cur: database cursor
  262. database_engine: synapse database engine class
  263. modname (str): fully qualified name of the module
  264. names_and_streams (Iterable[(str, file)]): the names and streams of
  265. schemas to be applied
  266. """
  267. cur.execute(
  268. database_engine.convert_param_style(
  269. "SELECT file FROM applied_module_schemas WHERE module_name = ?"
  270. ),
  271. (modname,)
  272. )
  273. applied_deltas = set(d for d, in cur)
  274. for (name, stream) in names_and_streams:
  275. if name in applied_deltas:
  276. continue
  277. root_name, ext = os.path.splitext(name)
  278. if ext != '.sql':
  279. raise PrepareDatabaseException(
  280. "only .sql files are currently supported for module schemas",
  281. )
  282. logger.info("applying schema %s for %s", name, modname)
  283. for statement in get_statements(stream):
  284. cur.execute(statement)
  285. # Mark as done.
  286. cur.execute(
  287. database_engine.convert_param_style(
  288. "INSERT INTO applied_module_schemas (module_name, file)"
  289. " VALUES (?,?)",
  290. ),
  291. (modname, name)
  292. )
  293. def get_statements(f):
  294. statement_buffer = ""
  295. in_comment = False # If we're in a /* ... */ style comment
  296. for line in f:
  297. line = line.strip()
  298. if in_comment:
  299. # Check if this line contains an end to the comment
  300. comments = line.split("*/", 1)
  301. if len(comments) == 1:
  302. continue
  303. line = comments[1]
  304. in_comment = False
  305. # Remove inline block comments
  306. line = re.sub(r"/\*.*\*/", " ", line)
  307. # Does this line start a comment?
  308. comments = line.split("/*", 1)
  309. if len(comments) > 1:
  310. line = comments[0]
  311. in_comment = True
  312. # Deal with line comments
  313. line = line.split("--", 1)[0]
  314. line = line.split("//", 1)[0]
  315. # Find *all* semicolons. We need to treat first and last entry
  316. # specially.
  317. statements = line.split(";")
  318. # We must prepend statement_buffer to the first statement
  319. first_statement = "%s %s" % (
  320. statement_buffer.strip(),
  321. statements[0].strip()
  322. )
  323. statements[0] = first_statement
  324. # Every entry, except the last, is a full statement
  325. for statement in statements[:-1]:
  326. yield statement.strip()
  327. # The last entry did *not* end in a semicolon, so we store it for the
  328. # next semicolon we find
  329. statement_buffer = statements[-1].strip()
  330. def executescript(txn, schema_path):
  331. with open(schema_path, 'r') as f:
  332. for statement in get_statements(f):
  333. txn.execute(statement)
  334. def _get_or_create_schema_state(txn, database_engine):
  335. # Bluntly try creating the schema_version tables.
  336. schema_path = os.path.join(
  337. dir_path, "schema", "schema_version.sql",
  338. )
  339. executescript(txn, schema_path)
  340. txn.execute("SELECT version, upgraded FROM schema_version")
  341. row = txn.fetchone()
  342. current_version = int(row[0]) if row else None
  343. upgraded = bool(row[1]) if row else None
  344. if current_version:
  345. txn.execute(
  346. database_engine.convert_param_style(
  347. "SELECT file FROM applied_schema_deltas WHERE version >= ?"
  348. ),
  349. (current_version,)
  350. )
  351. applied_deltas = [d for d, in txn]
  352. return current_version, applied_deltas, upgraded
  353. return None