prepare_database.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. # Copyright 2014 - 2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import importlib.util
  15. import logging
  16. import os
  17. import re
  18. from collections import Counter
  19. from typing import Collection, Generator, Iterable, List, Optional, TextIO, Tuple
  20. import attr
  21. from typing_extensions import Counter as CounterType
  22. from synapse.config.homeserver import HomeServerConfig
  23. from synapse.storage.database import LoggingDatabaseConnection
  24. from synapse.storage.engines import BaseDatabaseEngine
  25. from synapse.storage.engines.postgres import PostgresEngine
  26. from synapse.storage.schema import SCHEMA_COMPAT_VERSION, SCHEMA_VERSION
  27. from synapse.storage.types import Cursor
  28. logger = logging.getLogger(__name__)
  29. schema_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "schema")
  30. class PrepareDatabaseException(Exception):
  31. pass
  32. class UpgradeDatabaseException(PrepareDatabaseException):
  33. pass
  34. OUTDATED_SCHEMA_ON_WORKER_ERROR = (
  35. "Expected database schema version %i but got %i: run the main synapse process to "
  36. "upgrade the database schema before starting worker processes."
  37. )
  38. EMPTY_DATABASE_ON_WORKER_ERROR = (
  39. "Uninitialised database: run the main synapse process to prepare the database "
  40. "schema before starting worker processes."
  41. )
  42. UNAPPLIED_DELTA_ON_WORKER_ERROR = (
  43. "Database schema delta %s has not been applied: run the main synapse process to "
  44. "upgrade the database schema before starting worker processes."
  45. )
  46. @attr.s
  47. class _SchemaState:
  48. current_version: int = attr.ib()
  49. """The current schema version of the database"""
  50. compat_version: Optional[int] = attr.ib()
  51. """The SCHEMA_VERSION of the oldest version of Synapse for this database
  52. If this is None, we have an old version of the database without the necessary
  53. table.
  54. """
  55. applied_deltas: Collection[str] = attr.ib(factory=tuple)
  56. """Any delta files for `current_version` which have already been applied"""
  57. upgraded: bool = attr.ib(default=False)
  58. """Whether the current state was reached by applying deltas.
  59. If False, we have run the full schema for `current_version`, and have applied no
  60. deltas since. If True, we have run some deltas since the original creation."""
  61. def prepare_database(
  62. db_conn: LoggingDatabaseConnection,
  63. database_engine: BaseDatabaseEngine,
  64. config: Optional[HomeServerConfig],
  65. databases: Collection[str] = ("main", "state"),
  66. ):
  67. """Prepares a physical database for usage. Will either create all necessary tables
  68. or upgrade from an older schema version.
  69. If `config` is None then prepare_database will assert that no upgrade is
  70. necessary, *or* will create a fresh database if the database is empty.
  71. Args:
  72. db_conn:
  73. database_engine:
  74. config :
  75. application config, or None if we are connecting to an existing
  76. database which we expect to be configured already
  77. databases: The name of the databases that will be used
  78. with this physical database. Defaults to all databases.
  79. """
  80. try:
  81. cur = db_conn.cursor(txn_name="prepare_database")
  82. # sqlite does not automatically start transactions for DDL / SELECT statements,
  83. # so we start one before running anything. This ensures that any upgrades
  84. # are either applied completely, or not at all.
  85. #
  86. # (psycopg2 automatically starts a transaction as soon as we run any statements
  87. # at all, so this is redundant but harmless there.)
  88. cur.execute("BEGIN TRANSACTION")
  89. logger.info("%r: Checking existing schema version", databases)
  90. version_info = _get_or_create_schema_state(cur, database_engine)
  91. if version_info:
  92. logger.info(
  93. "%r: Existing schema is %i (+%i deltas)",
  94. databases,
  95. version_info.current_version,
  96. len(version_info.applied_deltas),
  97. )
  98. # config should only be None when we are preparing an in-memory SQLite db,
  99. # which should be empty.
  100. if config is None:
  101. raise ValueError(
  102. "config==None in prepare_database, but database is not empty"
  103. )
  104. # if it's a worker app, refuse to upgrade the database, to avoid multiple
  105. # workers doing it at once.
  106. if (
  107. config.worker.worker_app is not None
  108. and version_info.current_version != SCHEMA_VERSION
  109. ):
  110. raise UpgradeDatabaseException(
  111. OUTDATED_SCHEMA_ON_WORKER_ERROR
  112. % (SCHEMA_VERSION, version_info.current_version)
  113. )
  114. _upgrade_existing_database(
  115. cur,
  116. version_info,
  117. database_engine,
  118. config,
  119. databases=databases,
  120. )
  121. else:
  122. logger.info("%r: Initialising new database", databases)
  123. # if it's a worker app, refuse to upgrade the database, to avoid multiple
  124. # workers doing it at once.
  125. if config and config.worker.worker_app is not None:
  126. raise UpgradeDatabaseException(EMPTY_DATABASE_ON_WORKER_ERROR)
  127. _setup_new_database(cur, database_engine, databases=databases)
  128. # check if any of our configured dynamic modules want a database
  129. if config is not None:
  130. _apply_module_schemas(cur, database_engine, config)
  131. cur.close()
  132. db_conn.commit()
  133. except Exception:
  134. db_conn.rollback()
  135. raise
  136. def _setup_new_database(
  137. cur: Cursor, database_engine: BaseDatabaseEngine, databases: Collection[str]
  138. ) -> None:
  139. """Sets up the physical database by finding a base set of "full schemas" and
  140. then applying any necessary deltas, including schemas from the given data
  141. stores.
  142. The "full_schemas" directory has subdirectories named after versions. This
  143. function searches for the highest version less than or equal to
  144. `SCHEMA_VERSION` and executes all .sql files in that directory.
  145. The function will then apply all deltas for all versions after the base
  146. version.
  147. Example directory structure:
  148. schema/
  149. common/
  150. delta/
  151. ...
  152. full_schemas/
  153. 11/
  154. foo.sql
  155. main/
  156. delta/
  157. ...
  158. full_schemas/
  159. 3/
  160. test.sql
  161. ...
  162. 11/
  163. bar.sql
  164. ...
  165. In the example foo.sql and bar.sql would be run, and then any delta files
  166. for versions strictly greater than 11.
  167. Note: we apply the full schemas and deltas from the `schema/common`
  168. folder as well those in the databases specified.
  169. Args:
  170. cur: a database cursor
  171. database_engine
  172. databases: The names of the databases to instantiate on the given physical database.
  173. """
  174. # We're about to set up a brand new database so we check that its
  175. # configured to our liking.
  176. database_engine.check_new_database(cur)
  177. full_schemas_dir = os.path.join(schema_path, "common", "full_schemas")
  178. # First we find the highest full schema version we have
  179. valid_versions = []
  180. for filename in os.listdir(full_schemas_dir):
  181. try:
  182. ver = int(filename)
  183. except ValueError:
  184. continue
  185. if ver <= SCHEMA_VERSION:
  186. valid_versions.append(ver)
  187. if not valid_versions:
  188. raise PrepareDatabaseException(
  189. "Could not find a suitable base set of full schemas"
  190. )
  191. max_current_ver = max(valid_versions)
  192. logger.debug("Initialising schema v%d", max_current_ver)
  193. # Now let's find all the full schema files, both in the common schema and
  194. # in database schemas.
  195. directories = [os.path.join(full_schemas_dir, str(max_current_ver))]
  196. directories.extend(
  197. os.path.join(
  198. schema_path,
  199. database,
  200. "full_schemas",
  201. str(max_current_ver),
  202. )
  203. for database in databases
  204. )
  205. directory_entries: List[_DirectoryListing] = []
  206. for directory in directories:
  207. directory_entries.extend(
  208. _DirectoryListing(file_name, os.path.join(directory, file_name))
  209. for file_name in os.listdir(directory)
  210. )
  211. if isinstance(database_engine, PostgresEngine):
  212. specific = "postgres"
  213. else:
  214. specific = "sqlite"
  215. directory_entries.sort()
  216. for entry in directory_entries:
  217. if entry.file_name.endswith(".sql") or entry.file_name.endswith(
  218. ".sql." + specific
  219. ):
  220. logger.debug("Applying schema %s", entry.absolute_path)
  221. executescript(cur, entry.absolute_path)
  222. cur.execute(
  223. "INSERT INTO schema_version (version, upgraded) VALUES (?,?)",
  224. (max_current_ver, False),
  225. )
  226. _upgrade_existing_database(
  227. cur,
  228. _SchemaState(current_version=max_current_ver, compat_version=None),
  229. database_engine=database_engine,
  230. config=None,
  231. databases=databases,
  232. is_empty=True,
  233. )
  234. def _upgrade_existing_database(
  235. cur: Cursor,
  236. current_schema_state: _SchemaState,
  237. database_engine: BaseDatabaseEngine,
  238. config: Optional[HomeServerConfig],
  239. databases: Collection[str],
  240. is_empty: bool = False,
  241. ) -> None:
  242. """Upgrades an existing physical database.
  243. Delta files can either be SQL stored in *.sql files, or python modules
  244. in *.py.
  245. There can be multiple delta files per version. Synapse will keep track of
  246. which delta files have been applied, and will apply any that haven't been
  247. even if there has been no version bump. This is useful for development
  248. where orthogonal schema changes may happen on separate branches.
  249. Different delta files for the same version *must* be orthogonal and give
  250. the same result when applied in any order. No guarantees are made on the
  251. order of execution of these scripts.
  252. This is a no-op of current_version == SCHEMA_VERSION.
  253. Example directory structure:
  254. schema/
  255. delta/
  256. 11/
  257. foo.sql
  258. ...
  259. 12/
  260. foo.sql
  261. bar.py
  262. ...
  263. full_schemas/
  264. ...
  265. In the example, if current_version is 11, then foo.sql will be run if and
  266. only if `upgraded` is True. Then `foo.sql` and `bar.py` would be run in
  267. some arbitrary order.
  268. Note: we apply the delta files from the specified data stores as well as
  269. those in the top-level schema. We apply all delta files across data stores
  270. for a version before applying those in the next version.
  271. Args:
  272. cur
  273. current_schema_state: The current version of the schema, as
  274. returned by _get_or_create_schema_state
  275. database_engine
  276. config:
  277. None if we are initialising a blank database, otherwise the application
  278. config
  279. databases: The names of the databases to instantiate
  280. on the given physical database.
  281. is_empty: Is this a blank database? I.e. do we need to run the
  282. upgrade portions of the delta scripts.
  283. """
  284. if is_empty:
  285. assert not current_schema_state.applied_deltas
  286. else:
  287. assert config
  288. is_worker = config and config.worker.worker_app is not None
  289. if (
  290. current_schema_state.compat_version is not None
  291. and current_schema_state.compat_version > SCHEMA_VERSION
  292. ):
  293. raise ValueError(
  294. "Cannot use this database as it is too "
  295. + "new for the server to understand"
  296. )
  297. # some of the deltas assume that server_name is set correctly, so now
  298. # is a good time to run the sanity check.
  299. if not is_empty and "main" in databases:
  300. from synapse.storage.databases.main import check_database_before_upgrade
  301. assert config is not None
  302. check_database_before_upgrade(cur, database_engine, config)
  303. # update schema_compat_version before we run any upgrades, so that if synapse
  304. # gets downgraded again, it won't try to run against the upgraded database.
  305. if (
  306. current_schema_state.compat_version is None
  307. or current_schema_state.compat_version < SCHEMA_COMPAT_VERSION
  308. ):
  309. cur.execute("DELETE FROM schema_compat_version")
  310. cur.execute(
  311. "INSERT INTO schema_compat_version(compat_version) VALUES (?)",
  312. (SCHEMA_COMPAT_VERSION,),
  313. )
  314. start_ver = current_schema_state.current_version
  315. # if we got to this schema version by running a full_schema rather than a series
  316. # of deltas, we should not run the deltas for this version.
  317. if not current_schema_state.upgraded:
  318. start_ver += 1
  319. logger.debug("applied_delta_files: %s", current_schema_state.applied_deltas)
  320. if isinstance(database_engine, PostgresEngine):
  321. specific_engine_extension = ".postgres"
  322. else:
  323. specific_engine_extension = ".sqlite"
  324. specific_engine_extensions = (".sqlite", ".postgres")
  325. for v in range(start_ver, SCHEMA_VERSION + 1):
  326. if not is_worker:
  327. logger.info("Applying schema deltas for v%d", v)
  328. cur.execute("DELETE FROM schema_version")
  329. cur.execute(
  330. "INSERT INTO schema_version (version, upgraded) VALUES (?,?)",
  331. (v, True),
  332. )
  333. else:
  334. logger.info("Checking schema deltas for v%d", v)
  335. # We need to search both the global and per data store schema
  336. # directories for schema updates.
  337. # First we find the directories to search in
  338. delta_dir = os.path.join(schema_path, "common", "delta", str(v))
  339. directories = [delta_dir]
  340. for database in databases:
  341. directories.append(os.path.join(schema_path, database, "delta", str(v)))
  342. # Used to check if we have any duplicate file names
  343. file_name_counter: CounterType[str] = Counter()
  344. # Now find which directories have anything of interest.
  345. directory_entries: List[_DirectoryListing] = []
  346. for directory in directories:
  347. logger.debug("Looking for schema deltas in %s", directory)
  348. try:
  349. file_names = os.listdir(directory)
  350. directory_entries.extend(
  351. _DirectoryListing(file_name, os.path.join(directory, file_name))
  352. for file_name in file_names
  353. )
  354. for file_name in file_names:
  355. file_name_counter[file_name] += 1
  356. except FileNotFoundError:
  357. # Data stores can have empty entries for a given version delta.
  358. pass
  359. except OSError:
  360. raise UpgradeDatabaseException(
  361. "Could not open delta dir for version %d: %s" % (v, directory)
  362. )
  363. duplicates = {
  364. file_name for file_name, count in file_name_counter.items() if count > 1
  365. }
  366. if duplicates:
  367. # We don't support using the same file name in the same delta version.
  368. raise PrepareDatabaseException(
  369. "Found multiple delta files with the same name in v%d: %s"
  370. % (
  371. v,
  372. duplicates,
  373. )
  374. )
  375. # We sort to ensure that we apply the delta files in a consistent
  376. # order (to avoid bugs caused by inconsistent directory listing order)
  377. directory_entries.sort()
  378. for entry in directory_entries:
  379. file_name = entry.file_name
  380. relative_path = os.path.join(str(v), file_name)
  381. absolute_path = entry.absolute_path
  382. logger.debug("Found file: %s (%s)", relative_path, absolute_path)
  383. if relative_path in current_schema_state.applied_deltas:
  384. continue
  385. root_name, ext = os.path.splitext(file_name)
  386. if ext == ".py":
  387. # This is a python upgrade module. We need to import into some
  388. # package and then execute its `run_upgrade` function.
  389. if is_worker:
  390. raise PrepareDatabaseException(
  391. UNAPPLIED_DELTA_ON_WORKER_ERROR % relative_path
  392. )
  393. module_name = "synapse.storage.v%d_%s" % (v, root_name)
  394. spec = importlib.util.spec_from_file_location(
  395. module_name, absolute_path
  396. )
  397. if spec is None:
  398. raise RuntimeError(
  399. f"Could not build a module spec for {module_name} at {absolute_path}"
  400. )
  401. module = importlib.util.module_from_spec(spec)
  402. spec.loader.exec_module(module) # type: ignore
  403. logger.info("Running script %s", relative_path)
  404. module.run_create(cur, database_engine) # type: ignore
  405. if not is_empty:
  406. module.run_upgrade(cur, database_engine, config=config) # type: ignore
  407. elif ext == ".pyc" or file_name == "__pycache__":
  408. # Sometimes .pyc files turn up anyway even though we've
  409. # disabled their generation; e.g. from distribution package
  410. # installers. Silently skip it
  411. continue
  412. elif ext == ".sql":
  413. # A plain old .sql file, just read and execute it
  414. if is_worker:
  415. raise PrepareDatabaseException(
  416. UNAPPLIED_DELTA_ON_WORKER_ERROR % relative_path
  417. )
  418. logger.info("Applying schema %s", relative_path)
  419. executescript(cur, absolute_path)
  420. elif ext == specific_engine_extension and root_name.endswith(".sql"):
  421. # A .sql file specific to our engine; just read and execute it
  422. if is_worker:
  423. raise PrepareDatabaseException(
  424. UNAPPLIED_DELTA_ON_WORKER_ERROR % relative_path
  425. )
  426. logger.info("Applying engine-specific schema %s", relative_path)
  427. executescript(cur, absolute_path)
  428. elif ext in specific_engine_extensions and root_name.endswith(".sql"):
  429. # A .sql file for a different engine; skip it.
  430. continue
  431. else:
  432. # Not a valid delta file.
  433. logger.warning(
  434. "Found directory entry that did not end in .py or .sql: %s",
  435. relative_path,
  436. )
  437. continue
  438. # Mark as done.
  439. cur.execute(
  440. "INSERT INTO applied_schema_deltas (version, file) VALUES (?,?)",
  441. (v, relative_path),
  442. )
  443. logger.info("Schema now up to date")
  444. def _apply_module_schemas(
  445. txn: Cursor, database_engine: BaseDatabaseEngine, config: HomeServerConfig
  446. ) -> None:
  447. """Apply the module schemas for the dynamic modules, if any
  448. Args:
  449. cur: database cursor
  450. database_engine:
  451. config: application config
  452. """
  453. # This is the old way for password_auth_provider modules to make changes
  454. # to the database. This should instead be done using the module API
  455. for (mod, _config) in config.authproviders.password_providers:
  456. if not hasattr(mod, "get_db_schema_files"):
  457. continue
  458. modname = ".".join((mod.__module__, mod.__name__))
  459. _apply_module_schema_files(
  460. txn, database_engine, modname, mod.get_db_schema_files()
  461. )
  462. def _apply_module_schema_files(
  463. cur: Cursor,
  464. database_engine: BaseDatabaseEngine,
  465. modname: str,
  466. names_and_streams: Iterable[Tuple[str, TextIO]],
  467. ) -> None:
  468. """Apply the module schemas for a single module
  469. Args:
  470. cur: database cursor
  471. database_engine: synapse database engine class
  472. modname: fully qualified name of the module
  473. names_and_streams: the names and streams of schemas to be applied
  474. """
  475. cur.execute(
  476. "SELECT file FROM applied_module_schemas WHERE module_name = ?",
  477. (modname,),
  478. )
  479. applied_deltas = {d for d, in cur}
  480. for (name, stream) in names_and_streams:
  481. if name in applied_deltas:
  482. continue
  483. root_name, ext = os.path.splitext(name)
  484. if ext != ".sql":
  485. raise PrepareDatabaseException(
  486. "only .sql files are currently supported for module schemas"
  487. )
  488. logger.info("applying schema %s for %s", name, modname)
  489. execute_statements_from_stream(cur, stream)
  490. # Mark as done.
  491. cur.execute(
  492. "INSERT INTO applied_module_schemas (module_name, file) VALUES (?,?)",
  493. (modname, name),
  494. )
  495. def get_statements(f: Iterable[str]) -> Generator[str, None, None]:
  496. statement_buffer = ""
  497. in_comment = False # If we're in a /* ... */ style comment
  498. for line in f:
  499. line = line.strip()
  500. if in_comment:
  501. # Check if this line contains an end to the comment
  502. comments = line.split("*/", 1)
  503. if len(comments) == 1:
  504. continue
  505. line = comments[1]
  506. in_comment = False
  507. # Remove inline block comments
  508. line = re.sub(r"/\*.*\*/", " ", line)
  509. # Does this line start a comment?
  510. comments = line.split("/*", 1)
  511. if len(comments) > 1:
  512. line = comments[0]
  513. in_comment = True
  514. # Deal with line comments
  515. line = line.split("--", 1)[0]
  516. line = line.split("//", 1)[0]
  517. # Find *all* semicolons. We need to treat first and last entry
  518. # specially.
  519. statements = line.split(";")
  520. # We must prepend statement_buffer to the first statement
  521. first_statement = "%s %s" % (statement_buffer.strip(), statements[0].strip())
  522. statements[0] = first_statement
  523. # Every entry, except the last, is a full statement
  524. for statement in statements[:-1]:
  525. yield statement.strip()
  526. # The last entry did *not* end in a semicolon, so we store it for the
  527. # next semicolon we find
  528. statement_buffer = statements[-1].strip()
  529. def executescript(txn: Cursor, schema_path: str) -> None:
  530. with open(schema_path) as f:
  531. execute_statements_from_stream(txn, f)
  532. def execute_statements_from_stream(cur: Cursor, f: TextIO) -> None:
  533. for statement in get_statements(f):
  534. cur.execute(statement)
  535. def _get_or_create_schema_state(
  536. txn: Cursor, database_engine: BaseDatabaseEngine
  537. ) -> Optional[_SchemaState]:
  538. # Bluntly try creating the schema_version tables.
  539. sql_path = os.path.join(schema_path, "common", "schema_version.sql")
  540. executescript(txn, sql_path)
  541. txn.execute("SELECT version, upgraded FROM schema_version")
  542. row = txn.fetchone()
  543. if row is None:
  544. # new database
  545. return None
  546. current_version = int(row[0])
  547. upgraded = bool(row[1])
  548. compat_version: Optional[int] = None
  549. txn.execute("SELECT compat_version FROM schema_compat_version")
  550. row = txn.fetchone()
  551. if row is not None:
  552. compat_version = int(row[0])
  553. txn.execute(
  554. "SELECT file FROM applied_schema_deltas WHERE version >= ?",
  555. (current_version,),
  556. )
  557. applied_deltas = tuple(d for d, in txn)
  558. return _SchemaState(
  559. current_version=current_version,
  560. compat_version=compat_version,
  561. applied_deltas=applied_deltas,
  562. upgraded=upgraded,
  563. )
  564. @attr.s(slots=True)
  565. class _DirectoryListing:
  566. """Helper class to store schema file name and the
  567. absolute path to it.
  568. These entries get sorted, so for consistency we want to ensure that
  569. `file_name` attr is kept first.
  570. """
  571. file_name = attr.ib(type=str)
  572. absolute_path = attr.ib(type=str)