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.
 
 
 
 
 
 

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