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.
 
 
 
 
 
 

1146 lines
41 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  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 abc
  15. import logging
  16. from enum import Enum, IntEnum
  17. from types import TracebackType
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. AsyncContextManager,
  22. Awaitable,
  23. Callable,
  24. Dict,
  25. Iterable,
  26. List,
  27. Optional,
  28. Sequence,
  29. Tuple,
  30. Type,
  31. )
  32. import attr
  33. from pydantic import BaseModel
  34. from synapse.metrics.background_process_metrics import run_as_background_process
  35. from synapse.storage.engines import PostgresEngine
  36. from synapse.storage.types import Connection, Cursor
  37. from synapse.types import JsonDict
  38. from synapse.util import Clock, json_encoder
  39. from . import engines
  40. if TYPE_CHECKING:
  41. from synapse.server import HomeServer
  42. from synapse.storage.database import DatabasePool, LoggingTransaction
  43. logger = logging.getLogger(__name__)
  44. ON_UPDATE_CALLBACK = Callable[[str, str, bool], AsyncContextManager[int]]
  45. DEFAULT_BATCH_SIZE_CALLBACK = Callable[[str, str], Awaitable[int]]
  46. MIN_BATCH_SIZE_CALLBACK = Callable[[str, str], Awaitable[int]]
  47. class Constraint(metaclass=abc.ABCMeta):
  48. """Base class representing different constraints.
  49. Used by `register_background_validate_constraint_and_delete_rows`.
  50. """
  51. @abc.abstractmethod
  52. def make_check_clause(self, table: str) -> str:
  53. """Returns an SQL expression that checks the row passes the constraint."""
  54. @abc.abstractmethod
  55. def make_constraint_clause_postgres(self) -> str:
  56. """Returns an SQL clause for creating the constraint.
  57. Only used on Postgres DBs
  58. """
  59. @attr.s(auto_attribs=True)
  60. class ForeignKeyConstraint(Constraint):
  61. """A foreign key constraint.
  62. Attributes:
  63. referenced_table: The "parent" table name.
  64. columns: The list of mappings of columns from table to referenced table
  65. deferred: Whether to defer checking of the constraint to the end of the
  66. transaction. This is useful for e.g. backwards compatibility where
  67. an older version inserted data in the wrong order.
  68. """
  69. referenced_table: str
  70. columns: Sequence[Tuple[str, str]]
  71. deferred: bool
  72. def make_check_clause(self, table: str) -> str:
  73. join_clause = " AND ".join(
  74. f"{col1} = {table}.{col2}" for col1, col2 in self.columns
  75. )
  76. return f"EXISTS (SELECT 1 FROM {self.referenced_table} WHERE {join_clause})"
  77. def make_constraint_clause_postgres(self) -> str:
  78. column1_list = ", ".join(col1 for col1, col2 in self.columns)
  79. column2_list = ", ".join(col2 for col1, col2 in self.columns)
  80. defer_clause = " DEFERRABLE INITIALLY DEFERRED" if self.deferred else ""
  81. return f"FOREIGN KEY ({column1_list}) REFERENCES {self.referenced_table} ({column2_list}) {defer_clause}"
  82. @attr.s(auto_attribs=True)
  83. class NotNullConstraint(Constraint):
  84. """A NOT NULL column constraint"""
  85. column: str
  86. def make_check_clause(self, table: str) -> str:
  87. return f"{self.column} IS NOT NULL"
  88. def make_constraint_clause_postgres(self) -> str:
  89. return f"CHECK ({self.column} IS NOT NULL)"
  90. class ValidateConstraintProgress(BaseModel):
  91. """The format of the progress JSON for validate constraint background
  92. updates.
  93. Used by `register_background_validate_constraint_and_delete_rows`.
  94. """
  95. class State(str, Enum):
  96. check = "check"
  97. validate = "validate"
  98. state: State = State.validate
  99. lower_bound: Sequence[Any] = ()
  100. @attr.s(slots=True, frozen=True, auto_attribs=True)
  101. class _BackgroundUpdateHandler:
  102. """A handler for a given background update.
  103. Attributes:
  104. callback: The function to call to make progress on the background
  105. update.
  106. oneshot: Wether the update is likely to happen all in one go, ignoring
  107. the supplied target duration, e.g. index creation. This is used by
  108. the update controller to help correctly schedule the update.
  109. """
  110. callback: Callable[[JsonDict, int], Awaitable[int]]
  111. oneshot: bool = False
  112. class _BackgroundUpdateContextManager:
  113. def __init__(
  114. self, sleep: bool, clock: Clock, sleep_duration_ms: int, update_duration: int
  115. ):
  116. self._sleep = sleep
  117. self._clock = clock
  118. self._sleep_duration_ms = sleep_duration_ms
  119. self._update_duration_ms = update_duration
  120. async def __aenter__(self) -> int:
  121. if self._sleep:
  122. await self._clock.sleep(self._sleep_duration_ms / 1000)
  123. return self._update_duration_ms
  124. async def __aexit__(
  125. self,
  126. exc_type: Optional[Type[BaseException]],
  127. exc: Optional[BaseException],
  128. tb: Optional[TracebackType],
  129. ) -> None:
  130. pass
  131. class BackgroundUpdatePerformance:
  132. """Tracks the how long a background update is taking to update its items"""
  133. def __init__(self, name: str):
  134. self.name = name
  135. self.total_item_count = 0
  136. self.total_duration_ms = 0.0
  137. self.avg_item_count = 0.0
  138. self.avg_duration_ms = 0.0
  139. def update(self, item_count: int, duration_ms: float) -> None:
  140. """Update the stats after doing an update"""
  141. self.total_item_count += item_count
  142. self.total_duration_ms += duration_ms
  143. # Exponential moving averages for the number of items updated and
  144. # the duration.
  145. self.avg_item_count += 0.1 * (item_count - self.avg_item_count)
  146. self.avg_duration_ms += 0.1 * (duration_ms - self.avg_duration_ms)
  147. def average_items_per_ms(self) -> Optional[float]:
  148. """An estimate of how long it takes to do a single update.
  149. Returns:
  150. A duration in ms as a float
  151. """
  152. # We want to return None if this is the first background update item
  153. if self.total_item_count == 0:
  154. return None
  155. # Avoid dividing by zero
  156. elif self.avg_duration_ms == 0:
  157. return 0
  158. else:
  159. # Use the exponential moving average so that we can adapt to
  160. # changes in how long the update process takes.
  161. return float(self.avg_item_count) / float(self.avg_duration_ms)
  162. def total_items_per_ms(self) -> Optional[float]:
  163. """An estimate of how long it takes to do a single update.
  164. Returns:
  165. A duration in ms as a float
  166. """
  167. if self.total_duration_ms == 0:
  168. return 0
  169. elif self.total_item_count == 0:
  170. return None
  171. else:
  172. return float(self.total_item_count) / float(self.total_duration_ms)
  173. class UpdaterStatus(IntEnum):
  174. # Use negative values for error conditions.
  175. ABORTED = -1
  176. DISABLED = 0
  177. NOT_STARTED = 1
  178. RUNNING_UPDATE = 2
  179. COMPLETE = 3
  180. class BackgroundUpdater:
  181. """Background updates are updates to the database that run in the
  182. background. Each update processes a batch of data at once. We attempt to
  183. limit the impact of each update by monitoring how long each batch takes to
  184. process and autotuning the batch size.
  185. """
  186. def __init__(self, hs: "HomeServer", database: "DatabasePool"):
  187. self._clock = hs.get_clock()
  188. self.db_pool = database
  189. self.hs = hs
  190. self._database_name = database.name()
  191. # if a background update is currently running, its name.
  192. self._current_background_update: Optional[str] = None
  193. self._on_update_callback: Optional[ON_UPDATE_CALLBACK] = None
  194. self._default_batch_size_callback: Optional[DEFAULT_BATCH_SIZE_CALLBACK] = None
  195. self._min_batch_size_callback: Optional[MIN_BATCH_SIZE_CALLBACK] = None
  196. self._background_update_performance: Dict[str, BackgroundUpdatePerformance] = {}
  197. self._background_update_handlers: Dict[str, _BackgroundUpdateHandler] = {}
  198. # TODO: all these bool flags make me feel icky---can we combine into a status
  199. # enum?
  200. self._all_done = False
  201. # Whether we're currently running updates
  202. self._running = False
  203. # Marker to be set if we abort and halt all background updates.
  204. self._aborted = False
  205. # Whether background updates are enabled. This allows us to
  206. # enable/disable background updates via the admin API.
  207. self.enabled = True
  208. self.minimum_background_batch_size = hs.config.background_updates.min_batch_size
  209. self.default_background_batch_size = (
  210. hs.config.background_updates.default_batch_size
  211. )
  212. self.update_duration_ms = hs.config.background_updates.update_duration_ms
  213. self.sleep_duration_ms = hs.config.background_updates.sleep_duration_ms
  214. self.sleep_enabled = hs.config.background_updates.sleep_enabled
  215. def get_status(self) -> UpdaterStatus:
  216. """An integer summarising the updater status. Used as a metric."""
  217. if self._aborted:
  218. return UpdaterStatus.ABORTED
  219. # TODO: a status for "have seen at least one failure, but haven't aborted yet".
  220. if not self.enabled:
  221. return UpdaterStatus.DISABLED
  222. if self._all_done:
  223. return UpdaterStatus.COMPLETE
  224. if self._running:
  225. return UpdaterStatus.RUNNING_UPDATE
  226. return UpdaterStatus.NOT_STARTED
  227. def register_update_controller_callbacks(
  228. self,
  229. on_update: ON_UPDATE_CALLBACK,
  230. default_batch_size: Optional[DEFAULT_BATCH_SIZE_CALLBACK] = None,
  231. min_batch_size: Optional[DEFAULT_BATCH_SIZE_CALLBACK] = None,
  232. ) -> None:
  233. """Register callbacks from a module for each hook."""
  234. if self._on_update_callback is not None:
  235. logger.warning(
  236. "More than one module tried to register callbacks for controlling"
  237. " background updates. Only the callbacks registered by the first module"
  238. " (in order of appearance in Synapse's configuration file) that tried to"
  239. " do so will be called."
  240. )
  241. return
  242. self._on_update_callback = on_update
  243. if default_batch_size is not None:
  244. self._default_batch_size_callback = default_batch_size
  245. if min_batch_size is not None:
  246. self._min_batch_size_callback = min_batch_size
  247. def _get_context_manager_for_update(
  248. self,
  249. sleep: bool,
  250. update_name: str,
  251. database_name: str,
  252. oneshot: bool,
  253. ) -> AsyncContextManager[int]:
  254. """Get a context manager to run a background update with.
  255. If a module has registered a `update_handler` callback, use the context manager
  256. it returns.
  257. Otherwise, returns a context manager that will return a default value, optionally
  258. sleeping if needed.
  259. Args:
  260. sleep: Whether we can sleep between updates.
  261. update_name: The name of the update.
  262. database_name: The name of the database the update is being run on.
  263. oneshot: Whether the update will complete all in one go, e.g. index creation.
  264. In such cases the returned target duration is ignored.
  265. Returns:
  266. The target duration in milliseconds that the background update should run for.
  267. Note: this is a *target*, and an iteration may take substantially longer or
  268. shorter.
  269. """
  270. if self._on_update_callback is not None:
  271. return self._on_update_callback(update_name, database_name, oneshot)
  272. return _BackgroundUpdateContextManager(
  273. sleep, self._clock, self.sleep_duration_ms, self.update_duration_ms
  274. )
  275. async def _default_batch_size(self, update_name: str, database_name: str) -> int:
  276. """The batch size to use for the first iteration of a new background
  277. update.
  278. """
  279. if self._default_batch_size_callback is not None:
  280. return await self._default_batch_size_callback(update_name, database_name)
  281. return self.default_background_batch_size
  282. async def _min_batch_size(self, update_name: str, database_name: str) -> int:
  283. """A lower bound on the batch size of a new background update.
  284. Used to ensure that progress is always made. Must be greater than 0.
  285. """
  286. if self._min_batch_size_callback is not None:
  287. return await self._min_batch_size_callback(update_name, database_name)
  288. return self.minimum_background_batch_size
  289. def get_current_update(self) -> Optional[BackgroundUpdatePerformance]:
  290. """Returns the current background update, if any."""
  291. update_name = self._current_background_update
  292. if not update_name:
  293. return None
  294. perf = self._background_update_performance.get(update_name)
  295. if not perf:
  296. perf = BackgroundUpdatePerformance(update_name)
  297. return perf
  298. def start_doing_background_updates(self) -> None:
  299. if self.enabled:
  300. # if we start a new background update, not all updates are done.
  301. self._all_done = False
  302. sleep = self.sleep_enabled
  303. run_as_background_process(
  304. "background_updates", self.run_background_updates, sleep
  305. )
  306. async def run_background_updates(self, sleep: bool) -> None:
  307. if self._running or not self.enabled:
  308. return
  309. self._running = True
  310. back_to_back_failures = 0
  311. try:
  312. logger.info(
  313. "Starting background schema updates for database %s",
  314. self._database_name,
  315. )
  316. while self.enabled:
  317. try:
  318. result = await self.do_next_background_update(sleep)
  319. back_to_back_failures = 0
  320. except Exception as e:
  321. logger.exception("Error doing update: %s", e)
  322. back_to_back_failures += 1
  323. if back_to_back_failures >= 5:
  324. self._aborted = True
  325. raise RuntimeError(
  326. "5 back-to-back background update failures; aborting."
  327. )
  328. else:
  329. if result:
  330. logger.info(
  331. "No more background updates to do."
  332. " Unscheduling background update task."
  333. )
  334. self._all_done = True
  335. return None
  336. finally:
  337. self._running = False
  338. async def has_completed_background_updates(self) -> bool:
  339. """Check if all the background updates have completed
  340. Returns:
  341. True if all background updates have completed
  342. """
  343. # if we've previously determined that there is nothing left to do, that
  344. # is easy
  345. if self._all_done:
  346. return True
  347. # obviously, if we are currently processing an update, we're not done.
  348. if self._current_background_update:
  349. return False
  350. # otherwise, check if there are updates to be run. This is important,
  351. # as we may be running on a worker which doesn't perform the bg updates
  352. # itself, but still wants to wait for them to happen.
  353. updates = await self.db_pool.simple_select_onecol(
  354. "background_updates",
  355. keyvalues=None,
  356. retcol="1",
  357. desc="has_completed_background_updates",
  358. )
  359. if not updates:
  360. self._all_done = True
  361. return True
  362. return False
  363. async def has_completed_background_update(self, update_name: str) -> bool:
  364. """Check if the given background update has finished running."""
  365. if self._all_done:
  366. return True
  367. if update_name == self._current_background_update:
  368. return False
  369. update_exists = await self.db_pool.simple_select_one_onecol(
  370. "background_updates",
  371. keyvalues={"update_name": update_name},
  372. retcol="1",
  373. desc="has_completed_background_update",
  374. allow_none=True,
  375. )
  376. return not update_exists
  377. async def do_next_background_update(self, sleep: bool = True) -> bool:
  378. """Does some amount of work on the next queued background update
  379. Returns once some amount of work is done.
  380. Args:
  381. sleep: Whether to limit how quickly we run background updates or
  382. not.
  383. Returns:
  384. True if we have finished running all the background updates, otherwise False
  385. """
  386. def get_background_updates_txn(txn: Cursor) -> List[Dict[str, Any]]:
  387. txn.execute(
  388. """
  389. SELECT update_name, depends_on FROM background_updates
  390. ORDER BY ordering, update_name
  391. """
  392. )
  393. return self.db_pool.cursor_to_dict(txn)
  394. if not self._current_background_update:
  395. all_pending_updates = await self.db_pool.runInteraction(
  396. "background_updates",
  397. get_background_updates_txn,
  398. )
  399. if not all_pending_updates:
  400. # no work left to do
  401. return True
  402. # find the first update which isn't dependent on another one in the queue.
  403. pending = {update["update_name"] for update in all_pending_updates}
  404. for upd in all_pending_updates:
  405. depends_on = upd["depends_on"]
  406. if not depends_on or depends_on not in pending:
  407. break
  408. logger.info(
  409. "Not starting on bg update %s until %s is done",
  410. upd["update_name"],
  411. depends_on,
  412. )
  413. else:
  414. # if we get to the end of that for loop, there is a problem
  415. raise Exception(
  416. "Unable to find a background update which doesn't depend on "
  417. "another: dependency cycle?"
  418. )
  419. self._current_background_update = upd["update_name"]
  420. # We have a background update to run, otherwise we would have returned
  421. # early.
  422. assert self._current_background_update is not None
  423. update_info = self._background_update_handlers[self._current_background_update]
  424. async with self._get_context_manager_for_update(
  425. sleep=sleep,
  426. update_name=self._current_background_update,
  427. database_name=self._database_name,
  428. oneshot=update_info.oneshot,
  429. ) as desired_duration_ms:
  430. await self._do_background_update(desired_duration_ms)
  431. return False
  432. async def _do_background_update(self, desired_duration_ms: float) -> int:
  433. assert self._current_background_update is not None
  434. update_name = self._current_background_update
  435. logger.info("Starting update batch on background update '%s'", update_name)
  436. update_handler = self._background_update_handlers[update_name].callback
  437. performance = self._background_update_performance.get(update_name)
  438. if performance is None:
  439. performance = BackgroundUpdatePerformance(update_name)
  440. self._background_update_performance[update_name] = performance
  441. items_per_ms = performance.average_items_per_ms()
  442. if items_per_ms is not None:
  443. batch_size = int(desired_duration_ms * items_per_ms)
  444. # Clamp the batch size so that we always make progress
  445. batch_size = max(
  446. batch_size,
  447. await self._min_batch_size(update_name, self._database_name),
  448. )
  449. else:
  450. batch_size = await self._default_batch_size(
  451. update_name, self._database_name
  452. )
  453. progress_json = await self.db_pool.simple_select_one_onecol(
  454. "background_updates",
  455. keyvalues={"update_name": update_name},
  456. retcol="progress_json",
  457. )
  458. # Avoid a circular import.
  459. from synapse.storage._base import db_to_json
  460. progress = db_to_json(progress_json)
  461. time_start = self._clock.time_msec()
  462. items_updated = await update_handler(progress, batch_size)
  463. time_stop = self._clock.time_msec()
  464. duration_ms = time_stop - time_start
  465. performance.update(items_updated, duration_ms)
  466. logger.info(
  467. "Running background update %r. Processed %r items in %rms."
  468. " (total_rate=%r/ms, current_rate=%r/ms, total_updated=%r, batch_size=%r)",
  469. update_name,
  470. items_updated,
  471. duration_ms,
  472. performance.total_items_per_ms(),
  473. performance.average_items_per_ms(),
  474. performance.total_item_count,
  475. batch_size,
  476. )
  477. return len(self._background_update_performance)
  478. def register_background_update_handler(
  479. self,
  480. update_name: str,
  481. update_handler: Callable[[JsonDict, int], Awaitable[int]],
  482. ) -> None:
  483. """Register a handler for doing a background update.
  484. The handler should take two arguments:
  485. * A dict of the current progress
  486. * An integer count of the number of items to update in this batch.
  487. The handler should return a deferred or coroutine which returns an integer count
  488. of items updated.
  489. The handler is responsible for updating the progress of the update.
  490. Args:
  491. update_name: The name of the update that this code handles.
  492. update_handler: The function that does the update.
  493. """
  494. self._background_update_handlers[update_name] = _BackgroundUpdateHandler(
  495. update_handler
  496. )
  497. def register_background_index_update(
  498. self,
  499. update_name: str,
  500. index_name: str,
  501. table: str,
  502. columns: Iterable[str],
  503. where_clause: Optional[str] = None,
  504. unique: bool = False,
  505. psql_only: bool = False,
  506. replaces_index: Optional[str] = None,
  507. ) -> None:
  508. """Helper for store classes to do a background index addition
  509. To use:
  510. 1. use a schema delta file to add a background update. Example:
  511. INSERT INTO background_updates (update_name, progress_json) VALUES
  512. ('my_new_index', '{}');
  513. 2. In the Store constructor, call this method
  514. Args:
  515. update_name: update_name to register for
  516. index_name: name of index to add
  517. table: table to add index to
  518. columns: columns/expressions to include in index
  519. where_clause: A WHERE clause to specify a partial unique index.
  520. unique: true to make a UNIQUE index
  521. psql_only: true to only create this index on psql databases (useful
  522. for virtual sqlite tables)
  523. replaces_index: The name of an index that this index replaces.
  524. The named index will be dropped upon completion of the new index.
  525. """
  526. async def updater(progress: JsonDict, batch_size: int) -> int:
  527. await self.create_index_in_background(
  528. index_name=index_name,
  529. table=table,
  530. columns=columns,
  531. where_clause=where_clause,
  532. unique=unique,
  533. psql_only=psql_only,
  534. replaces_index=replaces_index,
  535. )
  536. await self._end_background_update(update_name)
  537. return 1
  538. self._background_update_handlers[update_name] = _BackgroundUpdateHandler(
  539. updater, oneshot=True
  540. )
  541. def register_background_validate_constraint(
  542. self, update_name: str, constraint_name: str, table: str
  543. ) -> None:
  544. """Helper for store classes to do a background validate constraint.
  545. This only applies on PostgreSQL.
  546. To use:
  547. 1. use a schema delta file to add a background update. Example:
  548. INSERT INTO background_updates (update_name, progress_json) VALUES
  549. ('validate_my_constraint', '{}');
  550. 2. In the Store constructor, call this method
  551. Args:
  552. update_name: update_name to register for
  553. constraint_name: name of constraint to validate
  554. table: table the constraint is applied to
  555. """
  556. def runner(conn: Connection) -> None:
  557. c = conn.cursor()
  558. sql = f"""
  559. ALTER TABLE {table} VALIDATE CONSTRAINT {constraint_name};
  560. """
  561. logger.debug("[SQL] %s", sql)
  562. c.execute(sql)
  563. async def updater(progress: JsonDict, batch_size: int) -> int:
  564. assert isinstance(
  565. self.db_pool.engine, engines.PostgresEngine
  566. ), "validate constraint background update registered for non-Postres database"
  567. logger.info("Validating constraint %s to %s", constraint_name, table)
  568. await self.db_pool.runWithConnection(runner)
  569. await self._end_background_update(update_name)
  570. return 1
  571. self._background_update_handlers[update_name] = _BackgroundUpdateHandler(
  572. updater, oneshot=True
  573. )
  574. async def create_index_in_background(
  575. self,
  576. index_name: str,
  577. table: str,
  578. columns: Iterable[str],
  579. where_clause: Optional[str] = None,
  580. unique: bool = False,
  581. psql_only: bool = False,
  582. replaces_index: Optional[str] = None,
  583. ) -> None:
  584. """Add an index in the background.
  585. Args:
  586. update_name: update_name to register for
  587. index_name: name of index to add
  588. table: table to add index to
  589. columns: columns/expressions to include in index
  590. where_clause: A WHERE clause to specify a partial unique index.
  591. unique: true to make a UNIQUE index
  592. psql_only: true to only create this index on psql databases (useful
  593. for virtual sqlite tables)
  594. replaces_index: The name of an index that this index replaces.
  595. The named index will be dropped upon completion of the new index.
  596. """
  597. def create_index_psql(conn: Connection) -> None:
  598. conn.rollback()
  599. # postgres insists on autocommit for the index
  600. conn.set_session(autocommit=True) # type: ignore
  601. try:
  602. c = conn.cursor()
  603. # If a previous attempt to create the index was interrupted,
  604. # we may already have a half-built index. Let's just drop it
  605. # before trying to create it again.
  606. sql = "DROP INDEX IF EXISTS %s" % (index_name,)
  607. logger.debug("[SQL] %s", sql)
  608. c.execute(sql)
  609. # override the global statement timeout to avoid accidentally squashing
  610. # a long-running index creation process
  611. timeout_sql = "SET SESSION statement_timeout = 0"
  612. c.execute(timeout_sql)
  613. sql = (
  614. "CREATE %(unique)s INDEX CONCURRENTLY %(name)s"
  615. " ON %(table)s"
  616. " (%(columns)s) %(where_clause)s"
  617. ) % {
  618. "unique": "UNIQUE" if unique else "",
  619. "name": index_name,
  620. "table": table,
  621. "columns": ", ".join(columns),
  622. "where_clause": "WHERE " + where_clause if where_clause else "",
  623. }
  624. logger.debug("[SQL] %s", sql)
  625. c.execute(sql)
  626. if replaces_index is not None:
  627. # We drop the old index as the new index has now been created.
  628. sql = f"DROP INDEX IF EXISTS {replaces_index}"
  629. logger.debug("[SQL] %s", sql)
  630. c.execute(sql)
  631. finally:
  632. # mypy ignore - `statement_timeout` is defined on PostgresEngine
  633. # reset the global timeout to the default
  634. default_timeout = self.db_pool.engine.statement_timeout # type: ignore[attr-defined]
  635. undo_timeout_sql = f"SET statement_timeout = {default_timeout}"
  636. conn.cursor().execute(undo_timeout_sql)
  637. conn.set_session(autocommit=False) # type: ignore
  638. def create_index_sqlite(conn: Connection) -> None:
  639. # Sqlite doesn't support concurrent creation of indexes.
  640. #
  641. # We assume that sqlite doesn't give us invalid indices; however
  642. # we may still end up with the index existing but the
  643. # background_updates not having been recorded if synapse got shut
  644. # down at the wrong moment - hance we use IF NOT EXISTS. (SQLite
  645. # has supported CREATE TABLE|INDEX IF NOT EXISTS since 3.3.0.)
  646. sql = (
  647. "CREATE %(unique)s INDEX IF NOT EXISTS %(name)s ON %(table)s"
  648. " (%(columns)s) %(where_clause)s"
  649. ) % {
  650. "unique": "UNIQUE" if unique else "",
  651. "name": index_name,
  652. "table": table,
  653. "columns": ", ".join(columns),
  654. "where_clause": "WHERE " + where_clause if where_clause else "",
  655. }
  656. c = conn.cursor()
  657. logger.debug("[SQL] %s", sql)
  658. c.execute(sql)
  659. if replaces_index is not None:
  660. # We drop the old index as the new index has now been created.
  661. sql = f"DROP INDEX IF EXISTS {replaces_index}"
  662. logger.debug("[SQL] %s", sql)
  663. c.execute(sql)
  664. if isinstance(self.db_pool.engine, engines.PostgresEngine):
  665. runner: Optional[Callable[[Connection], None]] = create_index_psql
  666. elif psql_only:
  667. runner = None
  668. else:
  669. runner = create_index_sqlite
  670. if runner is None:
  671. return
  672. logger.info("Adding index %s to %s", index_name, table)
  673. await self.db_pool.runWithConnection(runner)
  674. def register_background_validate_constraint_and_delete_rows(
  675. self,
  676. update_name: str,
  677. table: str,
  678. constraint_name: str,
  679. constraint: Constraint,
  680. unique_columns: Sequence[str],
  681. ) -> None:
  682. """Helper for store classes to do a background validate constraint, and
  683. delete rows that do not pass the constraint check.
  684. Note: This deletes rows that don't match the constraint. This may not be
  685. appropriate in all situations, and so the suitability of using this
  686. method should be considered on a case-by-case basis.
  687. This only applies on PostgreSQL.
  688. For SQLite the table gets recreated as part of the schema delta and the
  689. data is copied over synchronously (or whatever the correct way to
  690. describe it as).
  691. Args:
  692. update_name: The name of the background update.
  693. table: The table with the invalid constraint.
  694. constraint_name: The name of the constraint
  695. constraint: A `Constraint` object matching the type of constraint.
  696. unique_columns: A sequence of columns that form a unique constraint
  697. on the table. Used to iterate over the table.
  698. """
  699. assert isinstance(
  700. self.db_pool.engine, engines.PostgresEngine
  701. ), "validate constraint background update registered for non-Postres database"
  702. async def updater(progress: JsonDict, batch_size: int) -> int:
  703. return await self.validate_constraint_and_delete_in_background(
  704. update_name=update_name,
  705. table=table,
  706. constraint_name=constraint_name,
  707. constraint=constraint,
  708. unique_columns=unique_columns,
  709. progress=progress,
  710. batch_size=batch_size,
  711. )
  712. self._background_update_handlers[update_name] = _BackgroundUpdateHandler(
  713. updater, oneshot=True
  714. )
  715. async def validate_constraint_and_delete_in_background(
  716. self,
  717. update_name: str,
  718. table: str,
  719. constraint_name: str,
  720. constraint: Constraint,
  721. unique_columns: Sequence[str],
  722. progress: JsonDict,
  723. batch_size: int,
  724. ) -> int:
  725. """Validates a table constraint that has been marked as `NOT VALID`,
  726. deleting rows that don't pass the constraint check.
  727. This will delete rows that do not meet the validation check.
  728. update_name: str,
  729. table: str,
  730. constraint_name: str,
  731. constraint: Constraint,
  732. unique_columns: Sequence[str],
  733. """
  734. # We validate the constraint by:
  735. # 1. Trying to validate the constraint as is. If this succeeds then
  736. # we're done.
  737. # 2. Otherwise, we manually scan the table to remove rows that don't
  738. # match the constraint.
  739. # 3. We try re-validating the constraint.
  740. parsed_progress = ValidateConstraintProgress.parse_obj(progress)
  741. if parsed_progress.state == ValidateConstraintProgress.State.check:
  742. return_columns = ", ".join(unique_columns)
  743. order_columns = ", ".join(unique_columns)
  744. where_clause = ""
  745. args: List[Any] = []
  746. if parsed_progress.lower_bound:
  747. where_clause = f"""WHERE ({order_columns}) > ({", ".join("?" for _ in unique_columns)})"""
  748. args.extend(parsed_progress.lower_bound)
  749. args.append(batch_size)
  750. sql = f"""
  751. SELECT
  752. {return_columns},
  753. {constraint.make_check_clause(table)} AS check
  754. FROM {table}
  755. {where_clause}
  756. ORDER BY {order_columns}
  757. LIMIT ?
  758. """
  759. def validate_constraint_in_background_check(
  760. txn: "LoggingTransaction",
  761. ) -> None:
  762. txn.execute(sql, args)
  763. rows = txn.fetchall()
  764. new_progress = parsed_progress.copy()
  765. if not rows:
  766. new_progress.state = ValidateConstraintProgress.State.validate
  767. self._background_update_progress_txn(
  768. txn, update_name, new_progress.dict()
  769. )
  770. return
  771. new_progress.lower_bound = rows[-1][:-1]
  772. to_delete = [row[:-1] for row in rows if not row[-1]]
  773. if to_delete:
  774. logger.warning(
  775. "Deleting %d rows that do not pass new constraint",
  776. len(to_delete),
  777. )
  778. self.db_pool.simple_delete_many_batch_txn(
  779. txn, table=table, keys=unique_columns, values=to_delete
  780. )
  781. self._background_update_progress_txn(
  782. txn, update_name, new_progress.dict()
  783. )
  784. await self.db_pool.runInteraction(
  785. "validate_constraint_in_background_check",
  786. validate_constraint_in_background_check,
  787. )
  788. return batch_size
  789. elif parsed_progress.state == ValidateConstraintProgress.State.validate:
  790. sql = f"ALTER TABLE {table} VALIDATE CONSTRAINT {constraint_name}"
  791. def validate_constraint_in_background_validate(
  792. txn: "LoggingTransaction",
  793. ) -> None:
  794. txn.execute(sql)
  795. try:
  796. await self.db_pool.runInteraction(
  797. "validate_constraint_in_background_validate",
  798. validate_constraint_in_background_validate,
  799. )
  800. await self._end_background_update(update_name)
  801. except self.db_pool.engine.module.IntegrityError as e:
  802. # If we get an integrity error here, then we go back and recheck the table.
  803. logger.warning("Integrity error when validating constraint: %s", e)
  804. await self._background_update_progress(
  805. update_name,
  806. ValidateConstraintProgress(
  807. state=ValidateConstraintProgress.State.check
  808. ).dict(),
  809. )
  810. return batch_size
  811. else:
  812. raise Exception(
  813. f"Unrecognized state '{parsed_progress.state}' when trying to validate_constraint_and_delete_in_background"
  814. )
  815. async def _end_background_update(self, update_name: str) -> None:
  816. """Removes a completed background update task from the queue.
  817. Args:
  818. update_name:: The name of the completed task to remove
  819. Returns:
  820. None, completes once the task is removed.
  821. """
  822. if update_name != self._current_background_update:
  823. raise Exception(
  824. "Cannot end background update %s which isn't currently running"
  825. % update_name
  826. )
  827. self._current_background_update = None
  828. await self.db_pool.simple_delete_one(
  829. "background_updates", keyvalues={"update_name": update_name}
  830. )
  831. async def _background_update_progress(
  832. self, update_name: str, progress: dict
  833. ) -> None:
  834. """Update the progress of a background update
  835. Args:
  836. update_name: The name of the background update task
  837. progress: The progress of the update.
  838. """
  839. await self.db_pool.runInteraction(
  840. "background_update_progress",
  841. self._background_update_progress_txn,
  842. update_name,
  843. progress,
  844. )
  845. def _background_update_progress_txn(
  846. self, txn: "LoggingTransaction", update_name: str, progress: JsonDict
  847. ) -> None:
  848. """Update the progress of a background update
  849. Args:
  850. txn: The transaction.
  851. update_name: The name of the background update task
  852. progress: The progress of the update.
  853. """
  854. progress_json = json_encoder.encode(progress)
  855. self.db_pool.simple_update_one_txn(
  856. txn,
  857. "background_updates",
  858. keyvalues={"update_name": update_name},
  859. updatevalues={"progress_json": progress_json},
  860. )
  861. def run_validate_constraint_and_delete_rows_schema_delta(
  862. txn: "LoggingTransaction",
  863. ordering: int,
  864. update_name: str,
  865. table: str,
  866. constraint_name: str,
  867. constraint: Constraint,
  868. sqlite_table_name: str,
  869. sqlite_table_schema: str,
  870. ) -> None:
  871. """Runs a schema delta to add a constraint to the table. This should be run
  872. in a schema delta file.
  873. For PostgreSQL the constraint is added and validated in the background.
  874. For SQLite the table is recreated and data copied across immediately. This
  875. is done by the caller passing in a script to create the new table. Note that
  876. table indexes and triggers are copied over automatically.
  877. There must be a corresponding call to
  878. `register_background_validate_constraint_and_delete_rows` to register the
  879. background update in one of the data store classes.
  880. Attributes:
  881. txn ordering, update_name: For adding a row to background_updates table.
  882. table: The table to add constraint to. constraint_name: The name of the
  883. new constraint constraint: A `Constraint` object describing the
  884. constraint sqlite_table_name: For SQLite the name of the empty copy of
  885. table sqlite_table_schema: A SQL script for creating the above table.
  886. """
  887. if isinstance(txn.database_engine, PostgresEngine):
  888. # For postgres we can just add the constraint and mark it as NOT VALID,
  889. # and then insert a background update to go and check the validity in
  890. # the background.
  891. txn.execute(
  892. f"""
  893. ALTER TABLE {table}
  894. ADD CONSTRAINT {constraint_name} {constraint.make_constraint_clause_postgres()}
  895. NOT VALID
  896. """
  897. )
  898. txn.execute(
  899. "INSERT INTO background_updates (ordering, update_name, progress_json) VALUES (?, ?, '{}')",
  900. (ordering, update_name),
  901. )
  902. else:
  903. # For SQLite, we:
  904. # 1. fetch all indexes/triggers/etc related to the table
  905. # 2. create an empty copy of the table
  906. # 3. copy across the rows (that satisfy the check)
  907. # 4. replace the old table with the new able.
  908. # 5. add back all the indexes/triggers/etc
  909. # Fetch the indexes/triggers/etc. Note that `sql` column being null is
  910. # due to indexes being auto created based on the class definition (e.g.
  911. # PRIMARY KEY), and so don't need to be recreated.
  912. txn.execute(
  913. """
  914. SELECT sql FROM sqlite_master
  915. WHERE tbl_name = ? AND type != 'table' AND sql IS NOT NULL
  916. """,
  917. (table,),
  918. )
  919. extras = [row[0] for row in txn]
  920. txn.execute(sqlite_table_schema)
  921. sql = f"""
  922. INSERT INTO {sqlite_table_name} SELECT * FROM {table}
  923. WHERE {constraint.make_check_clause(table)}
  924. """
  925. txn.execute(sql)
  926. txn.execute(f"DROP TABLE {table}")
  927. txn.execute(f"ALTER TABLE {sqlite_table_name} RENAME TO {table}")
  928. for extra in extras:
  929. txn.execute(extra)