background_updates.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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 logging
  15. from types import TracebackType
  16. from typing import (
  17. TYPE_CHECKING,
  18. Any,
  19. AsyncContextManager,
  20. Awaitable,
  21. Callable,
  22. Dict,
  23. Iterable,
  24. List,
  25. Optional,
  26. Type,
  27. )
  28. import attr
  29. from synapse.metrics.background_process_metrics import run_as_background_process
  30. from synapse.storage.types import Connection, Cursor
  31. from synapse.types import JsonDict
  32. from synapse.util import Clock, json_encoder
  33. from . import engines
  34. if TYPE_CHECKING:
  35. from synapse.server import HomeServer
  36. from synapse.storage.database import DatabasePool, LoggingTransaction
  37. logger = logging.getLogger(__name__)
  38. ON_UPDATE_CALLBACK = Callable[[str, str, bool], AsyncContextManager[int]]
  39. DEFAULT_BATCH_SIZE_CALLBACK = Callable[[str, str], Awaitable[int]]
  40. MIN_BATCH_SIZE_CALLBACK = Callable[[str, str], Awaitable[int]]
  41. @attr.s(slots=True, frozen=True, auto_attribs=True)
  42. class _BackgroundUpdateHandler:
  43. """A handler for a given background update.
  44. Attributes:
  45. callback: The function to call to make progress on the background
  46. update.
  47. oneshot: Wether the update is likely to happen all in one go, ignoring
  48. the supplied target duration, e.g. index creation. This is used by
  49. the update controller to help correctly schedule the update.
  50. """
  51. callback: Callable[[JsonDict, int], Awaitable[int]]
  52. oneshot: bool = False
  53. class _BackgroundUpdateContextManager:
  54. def __init__(
  55. self, sleep: bool, clock: Clock, sleep_duration_ms: int, update_duration: int
  56. ):
  57. self._sleep = sleep
  58. self._clock = clock
  59. self._sleep_duration_ms = sleep_duration_ms
  60. self._update_duration_ms = update_duration
  61. async def __aenter__(self) -> int:
  62. if self._sleep:
  63. await self._clock.sleep(self._sleep_duration_ms / 1000)
  64. return self._update_duration_ms
  65. async def __aexit__(
  66. self,
  67. exc_type: Optional[Type[BaseException]],
  68. exc: Optional[BaseException],
  69. tb: Optional[TracebackType],
  70. ) -> None:
  71. pass
  72. class BackgroundUpdatePerformance:
  73. """Tracks the how long a background update is taking to update its items"""
  74. def __init__(self, name: str):
  75. self.name = name
  76. self.total_item_count = 0
  77. self.total_duration_ms = 0.0
  78. self.avg_item_count = 0.0
  79. self.avg_duration_ms = 0.0
  80. def update(self, item_count: int, duration_ms: float) -> None:
  81. """Update the stats after doing an update"""
  82. self.total_item_count += item_count
  83. self.total_duration_ms += duration_ms
  84. # Exponential moving averages for the number of items updated and
  85. # the duration.
  86. self.avg_item_count += 0.1 * (item_count - self.avg_item_count)
  87. self.avg_duration_ms += 0.1 * (duration_ms - self.avg_duration_ms)
  88. def average_items_per_ms(self) -> Optional[float]:
  89. """An estimate of how long it takes to do a single update.
  90. Returns:
  91. A duration in ms as a float
  92. """
  93. # We want to return None if this is the first background update item
  94. if self.total_item_count == 0:
  95. return None
  96. # Avoid dividing by zero
  97. elif self.avg_duration_ms == 0:
  98. return 0
  99. else:
  100. # Use the exponential moving average so that we can adapt to
  101. # changes in how long the update process takes.
  102. return float(self.avg_item_count) / float(self.avg_duration_ms)
  103. def total_items_per_ms(self) -> Optional[float]:
  104. """An estimate of how long it takes to do a single update.
  105. Returns:
  106. A duration in ms as a float
  107. """
  108. if self.total_duration_ms == 0:
  109. return 0
  110. elif self.total_item_count == 0:
  111. return None
  112. else:
  113. return float(self.total_item_count) / float(self.total_duration_ms)
  114. class BackgroundUpdater:
  115. """Background updates are updates to the database that run in the
  116. background. Each update processes a batch of data at once. We attempt to
  117. limit the impact of each update by monitoring how long each batch takes to
  118. process and autotuning the batch size.
  119. """
  120. def __init__(self, hs: "HomeServer", database: "DatabasePool"):
  121. self._clock = hs.get_clock()
  122. self.db_pool = database
  123. self._database_name = database.name()
  124. # if a background update is currently running, its name.
  125. self._current_background_update: Optional[str] = None
  126. self._on_update_callback: Optional[ON_UPDATE_CALLBACK] = None
  127. self._default_batch_size_callback: Optional[DEFAULT_BATCH_SIZE_CALLBACK] = None
  128. self._min_batch_size_callback: Optional[MIN_BATCH_SIZE_CALLBACK] = None
  129. self._background_update_performance: Dict[str, BackgroundUpdatePerformance] = {}
  130. self._background_update_handlers: Dict[str, _BackgroundUpdateHandler] = {}
  131. self._all_done = False
  132. # Whether we're currently running updates
  133. self._running = False
  134. # Whether background updates are enabled. This allows us to
  135. # enable/disable background updates via the admin API.
  136. self.enabled = True
  137. self.minimum_background_batch_size = hs.config.background_updates.min_batch_size
  138. self.default_background_batch_size = (
  139. hs.config.background_updates.default_batch_size
  140. )
  141. self.update_duration_ms = hs.config.background_updates.update_duration_ms
  142. self.sleep_duration_ms = hs.config.background_updates.sleep_duration_ms
  143. self.sleep_enabled = hs.config.background_updates.sleep_enabled
  144. def register_update_controller_callbacks(
  145. self,
  146. on_update: ON_UPDATE_CALLBACK,
  147. default_batch_size: Optional[DEFAULT_BATCH_SIZE_CALLBACK] = None,
  148. min_batch_size: Optional[DEFAULT_BATCH_SIZE_CALLBACK] = None,
  149. ) -> None:
  150. """Register callbacks from a module for each hook."""
  151. if self._on_update_callback is not None:
  152. logger.warning(
  153. "More than one module tried to register callbacks for controlling"
  154. " background updates. Only the callbacks registered by the first module"
  155. " (in order of appearance in Synapse's configuration file) that tried to"
  156. " do so will be called."
  157. )
  158. return
  159. self._on_update_callback = on_update
  160. if default_batch_size is not None:
  161. self._default_batch_size_callback = default_batch_size
  162. if min_batch_size is not None:
  163. self._min_batch_size_callback = min_batch_size
  164. def _get_context_manager_for_update(
  165. self,
  166. sleep: bool,
  167. update_name: str,
  168. database_name: str,
  169. oneshot: bool,
  170. ) -> AsyncContextManager[int]:
  171. """Get a context manager to run a background update with.
  172. If a module has registered a `update_handler` callback, use the context manager
  173. it returns.
  174. Otherwise, returns a context manager that will return a default value, optionally
  175. sleeping if needed.
  176. Args:
  177. sleep: Whether we can sleep between updates.
  178. update_name: The name of the update.
  179. database_name: The name of the database the update is being run on.
  180. oneshot: Whether the update will complete all in one go, e.g. index creation.
  181. In such cases the returned target duration is ignored.
  182. Returns:
  183. The target duration in milliseconds that the background update should run for.
  184. Note: this is a *target*, and an iteration may take substantially longer or
  185. shorter.
  186. """
  187. if self._on_update_callback is not None:
  188. return self._on_update_callback(update_name, database_name, oneshot)
  189. return _BackgroundUpdateContextManager(
  190. sleep, self._clock, self.sleep_duration_ms, self.update_duration_ms
  191. )
  192. async def _default_batch_size(self, update_name: str, database_name: str) -> int:
  193. """The batch size to use for the first iteration of a new background
  194. update.
  195. """
  196. if self._default_batch_size_callback is not None:
  197. return await self._default_batch_size_callback(update_name, database_name)
  198. return self.default_background_batch_size
  199. async def _min_batch_size(self, update_name: str, database_name: str) -> int:
  200. """A lower bound on the batch size of a new background update.
  201. Used to ensure that progress is always made. Must be greater than 0.
  202. """
  203. if self._min_batch_size_callback is not None:
  204. return await self._min_batch_size_callback(update_name, database_name)
  205. return self.minimum_background_batch_size
  206. def get_current_update(self) -> Optional[BackgroundUpdatePerformance]:
  207. """Returns the current background update, if any."""
  208. update_name = self._current_background_update
  209. if not update_name:
  210. return None
  211. perf = self._background_update_performance.get(update_name)
  212. if not perf:
  213. perf = BackgroundUpdatePerformance(update_name)
  214. return perf
  215. def start_doing_background_updates(self) -> None:
  216. if self.enabled:
  217. # if we start a new background update, not all updates are done.
  218. self._all_done = False
  219. sleep = self.sleep_enabled
  220. run_as_background_process(
  221. "background_updates", self.run_background_updates, sleep
  222. )
  223. async def run_background_updates(self, sleep: bool) -> None:
  224. if self._running or not self.enabled:
  225. return
  226. self._running = True
  227. back_to_back_failures = 0
  228. try:
  229. logger.info(
  230. "Starting background schema updates for database %s",
  231. self._database_name,
  232. )
  233. while self.enabled:
  234. try:
  235. result = await self.do_next_background_update(sleep)
  236. back_to_back_failures = 0
  237. except Exception:
  238. back_to_back_failures += 1
  239. if back_to_back_failures >= 5:
  240. raise RuntimeError(
  241. "5 back-to-back background update failures; aborting."
  242. )
  243. logger.exception("Error doing update")
  244. else:
  245. if result:
  246. logger.info(
  247. "No more background updates to do."
  248. " Unscheduling background update task."
  249. )
  250. self._all_done = True
  251. return None
  252. finally:
  253. self._running = False
  254. async def has_completed_background_updates(self) -> bool:
  255. """Check if all the background updates have completed
  256. Returns:
  257. True if all background updates have completed
  258. """
  259. # if we've previously determined that there is nothing left to do, that
  260. # is easy
  261. if self._all_done:
  262. return True
  263. # obviously, if we are currently processing an update, we're not done.
  264. if self._current_background_update:
  265. return False
  266. # otherwise, check if there are updates to be run. This is important,
  267. # as we may be running on a worker which doesn't perform the bg updates
  268. # itself, but still wants to wait for them to happen.
  269. updates = await self.db_pool.simple_select_onecol(
  270. "background_updates",
  271. keyvalues=None,
  272. retcol="1",
  273. desc="has_completed_background_updates",
  274. )
  275. if not updates:
  276. self._all_done = True
  277. return True
  278. return False
  279. async def has_completed_background_update(self, update_name: str) -> bool:
  280. """Check if the given background update has finished running."""
  281. if self._all_done:
  282. return True
  283. if update_name == self._current_background_update:
  284. return False
  285. update_exists = await self.db_pool.simple_select_one_onecol(
  286. "background_updates",
  287. keyvalues={"update_name": update_name},
  288. retcol="1",
  289. desc="has_completed_background_update",
  290. allow_none=True,
  291. )
  292. return not update_exists
  293. async def do_next_background_update(self, sleep: bool = True) -> bool:
  294. """Does some amount of work on the next queued background update
  295. Returns once some amount of work is done.
  296. Args:
  297. sleep: Whether to limit how quickly we run background updates or
  298. not.
  299. Returns:
  300. True if we have finished running all the background updates, otherwise False
  301. """
  302. def get_background_updates_txn(txn: Cursor) -> List[Dict[str, Any]]:
  303. txn.execute(
  304. """
  305. SELECT update_name, depends_on FROM background_updates
  306. ORDER BY ordering, update_name
  307. """
  308. )
  309. return self.db_pool.cursor_to_dict(txn)
  310. if not self._current_background_update:
  311. all_pending_updates = await self.db_pool.runInteraction(
  312. "background_updates",
  313. get_background_updates_txn,
  314. )
  315. if not all_pending_updates:
  316. # no work left to do
  317. return True
  318. # find the first update which isn't dependent on another one in the queue.
  319. pending = {update["update_name"] for update in all_pending_updates}
  320. for upd in all_pending_updates:
  321. depends_on = upd["depends_on"]
  322. if not depends_on or depends_on not in pending:
  323. break
  324. logger.info(
  325. "Not starting on bg update %s until %s is done",
  326. upd["update_name"],
  327. depends_on,
  328. )
  329. else:
  330. # if we get to the end of that for loop, there is a problem
  331. raise Exception(
  332. "Unable to find a background update which doesn't depend on "
  333. "another: dependency cycle?"
  334. )
  335. self._current_background_update = upd["update_name"]
  336. # We have a background update to run, otherwise we would have returned
  337. # early.
  338. assert self._current_background_update is not None
  339. update_info = self._background_update_handlers[self._current_background_update]
  340. async with self._get_context_manager_for_update(
  341. sleep=sleep,
  342. update_name=self._current_background_update,
  343. database_name=self._database_name,
  344. oneshot=update_info.oneshot,
  345. ) as desired_duration_ms:
  346. await self._do_background_update(desired_duration_ms)
  347. return False
  348. async def _do_background_update(self, desired_duration_ms: float) -> int:
  349. assert self._current_background_update is not None
  350. update_name = self._current_background_update
  351. logger.info("Starting update batch on background update '%s'", update_name)
  352. update_handler = self._background_update_handlers[update_name].callback
  353. performance = self._background_update_performance.get(update_name)
  354. if performance is None:
  355. performance = BackgroundUpdatePerformance(update_name)
  356. self._background_update_performance[update_name] = performance
  357. items_per_ms = performance.average_items_per_ms()
  358. if items_per_ms is not None:
  359. batch_size = int(desired_duration_ms * items_per_ms)
  360. # Clamp the batch size so that we always make progress
  361. batch_size = max(
  362. batch_size,
  363. await self._min_batch_size(update_name, self._database_name),
  364. )
  365. else:
  366. batch_size = await self._default_batch_size(
  367. update_name, self._database_name
  368. )
  369. progress_json = await self.db_pool.simple_select_one_onecol(
  370. "background_updates",
  371. keyvalues={"update_name": update_name},
  372. retcol="progress_json",
  373. )
  374. # Avoid a circular import.
  375. from synapse.storage._base import db_to_json
  376. progress = db_to_json(progress_json)
  377. time_start = self._clock.time_msec()
  378. items_updated = await update_handler(progress, batch_size)
  379. time_stop = self._clock.time_msec()
  380. duration_ms = time_stop - time_start
  381. performance.update(items_updated, duration_ms)
  382. logger.info(
  383. "Running background update %r. Processed %r items in %rms."
  384. " (total_rate=%r/ms, current_rate=%r/ms, total_updated=%r, batch_size=%r)",
  385. update_name,
  386. items_updated,
  387. duration_ms,
  388. performance.total_items_per_ms(),
  389. performance.average_items_per_ms(),
  390. performance.total_item_count,
  391. batch_size,
  392. )
  393. return len(self._background_update_performance)
  394. def register_background_update_handler(
  395. self,
  396. update_name: str,
  397. update_handler: Callable[[JsonDict, int], Awaitable[int]],
  398. ) -> None:
  399. """Register a handler for doing a background update.
  400. The handler should take two arguments:
  401. * A dict of the current progress
  402. * An integer count of the number of items to update in this batch.
  403. The handler should return a deferred or coroutine which returns an integer count
  404. of items updated.
  405. The handler is responsible for updating the progress of the update.
  406. Args:
  407. update_name: The name of the update that this code handles.
  408. update_handler: The function that does the update.
  409. """
  410. self._background_update_handlers[update_name] = _BackgroundUpdateHandler(
  411. update_handler
  412. )
  413. def register_background_index_update(
  414. self,
  415. update_name: str,
  416. index_name: str,
  417. table: str,
  418. columns: Iterable[str],
  419. where_clause: Optional[str] = None,
  420. unique: bool = False,
  421. psql_only: bool = False,
  422. replaces_index: Optional[str] = None,
  423. ) -> None:
  424. """Helper for store classes to do a background index addition
  425. To use:
  426. 1. use a schema delta file to add a background update. Example:
  427. INSERT INTO background_updates (update_name, progress_json) VALUES
  428. ('my_new_index', '{}');
  429. 2. In the Store constructor, call this method
  430. Args:
  431. update_name: update_name to register for
  432. index_name: name of index to add
  433. table: table to add index to
  434. columns: columns/expressions to include in index
  435. where_clause: A WHERE clause to specify a partial unique index.
  436. unique: true to make a UNIQUE index
  437. psql_only: true to only create this index on psql databases (useful
  438. for virtual sqlite tables)
  439. replaces_index: The name of an index that this index replaces.
  440. The named index will be dropped upon completion of the new index.
  441. """
  442. async def updater(progress: JsonDict, batch_size: int) -> int:
  443. await self.create_index_in_background(
  444. index_name=index_name,
  445. table=table,
  446. columns=columns,
  447. where_clause=where_clause,
  448. unique=unique,
  449. psql_only=psql_only,
  450. replaces_index=replaces_index,
  451. )
  452. await self._end_background_update(update_name)
  453. return 1
  454. self._background_update_handlers[update_name] = _BackgroundUpdateHandler(
  455. updater, oneshot=True
  456. )
  457. async def create_index_in_background(
  458. self,
  459. index_name: str,
  460. table: str,
  461. columns: Iterable[str],
  462. where_clause: Optional[str] = None,
  463. unique: bool = False,
  464. psql_only: bool = False,
  465. replaces_index: Optional[str] = None,
  466. ) -> None:
  467. """Add an index in the background.
  468. Args:
  469. update_name: update_name to register for
  470. index_name: name of index to add
  471. table: table to add index to
  472. columns: columns/expressions to include in index
  473. where_clause: A WHERE clause to specify a partial unique index.
  474. unique: true to make a UNIQUE index
  475. psql_only: true to only create this index on psql databases (useful
  476. for virtual sqlite tables)
  477. replaces_index: The name of an index that this index replaces.
  478. The named index will be dropped upon completion of the new index.
  479. """
  480. def create_index_psql(conn: Connection) -> None:
  481. conn.rollback()
  482. # postgres insists on autocommit for the index
  483. conn.set_session(autocommit=True) # type: ignore
  484. try:
  485. c = conn.cursor()
  486. # If a previous attempt to create the index was interrupted,
  487. # we may already have a half-built index. Let's just drop it
  488. # before trying to create it again.
  489. sql = "DROP INDEX IF EXISTS %s" % (index_name,)
  490. logger.debug("[SQL] %s", sql)
  491. c.execute(sql)
  492. sql = (
  493. "CREATE %(unique)s INDEX CONCURRENTLY %(name)s"
  494. " ON %(table)s"
  495. " (%(columns)s) %(where_clause)s"
  496. ) % {
  497. "unique": "UNIQUE" if unique else "",
  498. "name": index_name,
  499. "table": table,
  500. "columns": ", ".join(columns),
  501. "where_clause": "WHERE " + where_clause if where_clause else "",
  502. }
  503. logger.debug("[SQL] %s", sql)
  504. c.execute(sql)
  505. if replaces_index is not None:
  506. # We drop the old index as the new index has now been created.
  507. sql = f"DROP INDEX IF EXISTS {replaces_index}"
  508. logger.debug("[SQL] %s", sql)
  509. c.execute(sql)
  510. finally:
  511. conn.set_session(autocommit=False) # type: ignore
  512. def create_index_sqlite(conn: Connection) -> None:
  513. # Sqlite doesn't support concurrent creation of indexes.
  514. #
  515. # We assume that sqlite doesn't give us invalid indices; however
  516. # we may still end up with the index existing but the
  517. # background_updates not having been recorded if synapse got shut
  518. # down at the wrong moment - hance we use IF NOT EXISTS. (SQLite
  519. # has supported CREATE TABLE|INDEX IF NOT EXISTS since 3.3.0.)
  520. sql = (
  521. "CREATE %(unique)s INDEX IF NOT EXISTS %(name)s ON %(table)s"
  522. " (%(columns)s) %(where_clause)s"
  523. ) % {
  524. "unique": "UNIQUE" if unique else "",
  525. "name": index_name,
  526. "table": table,
  527. "columns": ", ".join(columns),
  528. "where_clause": "WHERE " + where_clause if where_clause else "",
  529. }
  530. c = conn.cursor()
  531. logger.debug("[SQL] %s", sql)
  532. c.execute(sql)
  533. if replaces_index is not None:
  534. # We drop the old index as the new index has now been created.
  535. sql = f"DROP INDEX IF EXISTS {replaces_index}"
  536. logger.debug("[SQL] %s", sql)
  537. c.execute(sql)
  538. if isinstance(self.db_pool.engine, engines.PostgresEngine):
  539. runner: Optional[Callable[[Connection], None]] = create_index_psql
  540. elif psql_only:
  541. runner = None
  542. else:
  543. runner = create_index_sqlite
  544. if runner is None:
  545. return
  546. logger.info("Adding index %s to %s", index_name, table)
  547. await self.db_pool.runWithConnection(runner)
  548. async def _end_background_update(self, update_name: str) -> None:
  549. """Removes a completed background update task from the queue.
  550. Args:
  551. update_name:: The name of the completed task to remove
  552. Returns:
  553. None, completes once the task is removed.
  554. """
  555. if update_name != self._current_background_update:
  556. raise Exception(
  557. "Cannot end background update %s which isn't currently running"
  558. % update_name
  559. )
  560. self._current_background_update = None
  561. await self.db_pool.simple_delete_one(
  562. "background_updates", keyvalues={"update_name": update_name}
  563. )
  564. async def _background_update_progress(
  565. self, update_name: str, progress: dict
  566. ) -> None:
  567. """Update the progress of a background update
  568. Args:
  569. update_name: The name of the background update task
  570. progress: The progress of the update.
  571. """
  572. await self.db_pool.runInteraction(
  573. "background_update_progress",
  574. self._background_update_progress_txn,
  575. update_name,
  576. progress,
  577. )
  578. def _background_update_progress_txn(
  579. self, txn: "LoggingTransaction", update_name: str, progress: JsonDict
  580. ) -> None:
  581. """Update the progress of a background update
  582. Args:
  583. txn: The transaction.
  584. update_name: The name of the background update task
  585. progress: The progress of the update.
  586. """
  587. progress_json = json_encoder.encode(progress)
  588. self.db_pool.simple_update_one_txn(
  589. txn,
  590. "background_updates",
  591. keyvalues={"update_name": update_name},
  592. updatevalues={"progress_json": progress_json},
  593. )