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.
 
 
 
 
 
 

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