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.
 
 
 
 
 
 

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