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.
 
 
 
 
 
 

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