You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

712 lines
25 KiB

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