background_updates.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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("Starting background schema updates")
  230. while self.enabled:
  231. try:
  232. result = await self.do_next_background_update(sleep)
  233. back_to_back_failures = 0
  234. except Exception:
  235. back_to_back_failures += 1
  236. if back_to_back_failures >= 5:
  237. raise RuntimeError(
  238. "5 back-to-back background update failures; aborting."
  239. )
  240. logger.exception("Error doing update")
  241. else:
  242. if result:
  243. logger.info(
  244. "No more background updates to do."
  245. " Unscheduling background update task."
  246. )
  247. self._all_done = True
  248. return None
  249. finally:
  250. self._running = False
  251. async def has_completed_background_updates(self) -> bool:
  252. """Check if all the background updates have completed
  253. Returns:
  254. True if all background updates have completed
  255. """
  256. # if we've previously determined that there is nothing left to do, that
  257. # is easy
  258. if self._all_done:
  259. return True
  260. # obviously, if we are currently processing an update, we're not done.
  261. if self._current_background_update:
  262. return False
  263. # otherwise, check if there are updates to be run. This is important,
  264. # as we may be running on a worker which doesn't perform the bg updates
  265. # itself, but still wants to wait for them to happen.
  266. updates = await self.db_pool.simple_select_onecol(
  267. "background_updates",
  268. keyvalues=None,
  269. retcol="1",
  270. desc="has_completed_background_updates",
  271. )
  272. if not updates:
  273. self._all_done = True
  274. return True
  275. return False
  276. async def has_completed_background_update(self, update_name: str) -> bool:
  277. """Check if the given background update has finished running."""
  278. if self._all_done:
  279. return True
  280. if update_name == self._current_background_update:
  281. return False
  282. update_exists = await self.db_pool.simple_select_one_onecol(
  283. "background_updates",
  284. keyvalues={"update_name": update_name},
  285. retcol="1",
  286. desc="has_completed_background_update",
  287. allow_none=True,
  288. )
  289. return not update_exists
  290. async def do_next_background_update(self, sleep: bool = True) -> bool:
  291. """Does some amount of work on the next queued background update
  292. Returns once some amount of work is done.
  293. Args:
  294. sleep: Whether to limit how quickly we run background updates or
  295. not.
  296. Returns:
  297. True if we have finished running all the background updates, otherwise False
  298. """
  299. def get_background_updates_txn(txn: Cursor) -> List[Dict[str, Any]]:
  300. txn.execute(
  301. """
  302. SELECT update_name, depends_on FROM background_updates
  303. ORDER BY ordering, update_name
  304. """
  305. )
  306. return self.db_pool.cursor_to_dict(txn)
  307. if not self._current_background_update:
  308. all_pending_updates = await self.db_pool.runInteraction(
  309. "background_updates",
  310. get_background_updates_txn,
  311. )
  312. if not all_pending_updates:
  313. # no work left to do
  314. return True
  315. # find the first update which isn't dependent on another one in the queue.
  316. pending = {update["update_name"] for update in all_pending_updates}
  317. for upd in all_pending_updates:
  318. depends_on = upd["depends_on"]
  319. if not depends_on or depends_on not in pending:
  320. break
  321. logger.info(
  322. "Not starting on bg update %s until %s is done",
  323. upd["update_name"],
  324. depends_on,
  325. )
  326. else:
  327. # if we get to the end of that for loop, there is a problem
  328. raise Exception(
  329. "Unable to find a background update which doesn't depend on "
  330. "another: dependency cycle?"
  331. )
  332. self._current_background_update = upd["update_name"]
  333. # We have a background update to run, otherwise we would have returned
  334. # early.
  335. assert self._current_background_update is not None
  336. update_info = self._background_update_handlers[self._current_background_update]
  337. async with self._get_context_manager_for_update(
  338. sleep=sleep,
  339. update_name=self._current_background_update,
  340. database_name=self._database_name,
  341. oneshot=update_info.oneshot,
  342. ) as desired_duration_ms:
  343. await self._do_background_update(desired_duration_ms)
  344. return False
  345. async def _do_background_update(self, desired_duration_ms: float) -> int:
  346. assert self._current_background_update is not None
  347. update_name = self._current_background_update
  348. logger.info("Starting update batch on background update '%s'", update_name)
  349. update_handler = self._background_update_handlers[update_name].callback
  350. performance = self._background_update_performance.get(update_name)
  351. if performance is None:
  352. performance = BackgroundUpdatePerformance(update_name)
  353. self._background_update_performance[update_name] = performance
  354. items_per_ms = performance.average_items_per_ms()
  355. if items_per_ms is not None:
  356. batch_size = int(desired_duration_ms * items_per_ms)
  357. # Clamp the batch size so that we always make progress
  358. batch_size = max(
  359. batch_size,
  360. await self._min_batch_size(update_name, self._database_name),
  361. )
  362. else:
  363. batch_size = await self._default_batch_size(
  364. update_name, self._database_name
  365. )
  366. progress_json = await self.db_pool.simple_select_one_onecol(
  367. "background_updates",
  368. keyvalues={"update_name": update_name},
  369. retcol="progress_json",
  370. )
  371. # Avoid a circular import.
  372. from synapse.storage._base import db_to_json
  373. progress = db_to_json(progress_json)
  374. time_start = self._clock.time_msec()
  375. items_updated = await update_handler(progress, batch_size)
  376. time_stop = self._clock.time_msec()
  377. duration_ms = time_stop - time_start
  378. performance.update(items_updated, duration_ms)
  379. logger.info(
  380. "Running background update %r. Processed %r items in %rms."
  381. " (total_rate=%r/ms, current_rate=%r/ms, total_updated=%r, batch_size=%r)",
  382. update_name,
  383. items_updated,
  384. duration_ms,
  385. performance.total_items_per_ms(),
  386. performance.average_items_per_ms(),
  387. performance.total_item_count,
  388. batch_size,
  389. )
  390. return len(self._background_update_performance)
  391. def register_background_update_handler(
  392. self,
  393. update_name: str,
  394. update_handler: Callable[[JsonDict, int], Awaitable[int]],
  395. ) -> None:
  396. """Register a handler for doing a background update.
  397. The handler should take two arguments:
  398. * A dict of the current progress
  399. * An integer count of the number of items to update in this batch.
  400. The handler should return a deferred or coroutine which returns an integer count
  401. of items updated.
  402. The handler is responsible for updating the progress of the update.
  403. Args:
  404. update_name: The name of the update that this code handles.
  405. update_handler: The function that does the update.
  406. """
  407. self._background_update_handlers[update_name] = _BackgroundUpdateHandler(
  408. update_handler
  409. )
  410. def register_noop_background_update(self, update_name: str) -> None:
  411. """Register a noop handler for a background update.
  412. This is useful when we previously did a background update, but no
  413. longer wish to do the update. In this case the background update should
  414. be removed from the schema delta files, but there may still be some
  415. users who have the background update queued, so this method should
  416. also be called to clear the update.
  417. Args:
  418. update_name: Name of update
  419. """
  420. async def noop_update(progress: JsonDict, batch_size: int) -> int:
  421. await self._end_background_update(update_name)
  422. return 1
  423. self.register_background_update_handler(update_name, noop_update)
  424. def register_background_index_update(
  425. self,
  426. update_name: str,
  427. index_name: str,
  428. table: str,
  429. columns: Iterable[str],
  430. where_clause: Optional[str] = None,
  431. unique: bool = False,
  432. psql_only: bool = False,
  433. replaces_index: Optional[str] = None,
  434. ) -> None:
  435. """Helper for store classes to do a background index addition
  436. To use:
  437. 1. use a schema delta file to add a background update. Example:
  438. INSERT INTO background_updates (update_name, progress_json) VALUES
  439. ('my_new_index', '{}');
  440. 2. In the Store constructor, call this method
  441. Args:
  442. update_name: update_name to register for
  443. index_name: name of index to add
  444. table: table to add index to
  445. columns: columns/expressions to include in index
  446. unique: true to make a UNIQUE index
  447. psql_only: true to only create this index on psql databases (useful
  448. for virtual sqlite tables)
  449. replaces_index: The name of an index that this index replaces.
  450. The named index will be dropped upon completion of the new index.
  451. """
  452. def create_index_psql(conn: Connection) -> None:
  453. conn.rollback()
  454. # postgres insists on autocommit for the index
  455. conn.set_session(autocommit=True) # type: ignore
  456. try:
  457. c = conn.cursor()
  458. # If a previous attempt to create the index was interrupted,
  459. # we may already have a half-built index. Let's just drop it
  460. # before trying to create it again.
  461. sql = "DROP INDEX IF EXISTS %s" % (index_name,)
  462. logger.debug("[SQL] %s", sql)
  463. c.execute(sql)
  464. sql = (
  465. "CREATE %(unique)s INDEX CONCURRENTLY %(name)s"
  466. " ON %(table)s"
  467. " (%(columns)s) %(where_clause)s"
  468. ) % {
  469. "unique": "UNIQUE" if unique else "",
  470. "name": index_name,
  471. "table": table,
  472. "columns": ", ".join(columns),
  473. "where_clause": "WHERE " + where_clause if where_clause else "",
  474. }
  475. logger.debug("[SQL] %s", sql)
  476. c.execute(sql)
  477. if replaces_index is not None:
  478. # We drop the old index as the new index has now been created.
  479. sql = f"DROP INDEX IF EXISTS {replaces_index}"
  480. logger.debug("[SQL] %s", sql)
  481. c.execute(sql)
  482. finally:
  483. conn.set_session(autocommit=False) # type: ignore
  484. def create_index_sqlite(conn: Connection) -> None:
  485. # Sqlite doesn't support concurrent creation of indexes.
  486. #
  487. # We don't use partial indices on SQLite as it wasn't introduced
  488. # until 3.8, and wheezy and CentOS 7 have 3.7
  489. #
  490. # We assume that sqlite doesn't give us invalid indices; however
  491. # we may still end up with the index existing but the
  492. # background_updates not having been recorded if synapse got shut
  493. # down at the wrong moment - hance we use IF NOT EXISTS. (SQLite
  494. # has supported CREATE TABLE|INDEX IF NOT EXISTS since 3.3.0.)
  495. sql = (
  496. "CREATE %(unique)s INDEX IF NOT EXISTS %(name)s ON %(table)s"
  497. " (%(columns)s)"
  498. ) % {
  499. "unique": "UNIQUE" if unique else "",
  500. "name": index_name,
  501. "table": table,
  502. "columns": ", ".join(columns),
  503. }
  504. c = conn.cursor()
  505. logger.debug("[SQL] %s", sql)
  506. c.execute(sql)
  507. if replaces_index is not None:
  508. # We drop the old index as the new index has now been created.
  509. sql = f"DROP INDEX IF EXISTS {replaces_index}"
  510. logger.debug("[SQL] %s", sql)
  511. c.execute(sql)
  512. if isinstance(self.db_pool.engine, engines.PostgresEngine):
  513. runner: Optional[Callable[[Connection], None]] = create_index_psql
  514. elif psql_only:
  515. runner = None
  516. else:
  517. runner = create_index_sqlite
  518. async def updater(progress: JsonDict, batch_size: int) -> int:
  519. if runner is not None:
  520. logger.info("Adding index %s to %s", index_name, table)
  521. await self.db_pool.runWithConnection(runner)
  522. await self._end_background_update(update_name)
  523. return 1
  524. self._background_update_handlers[update_name] = _BackgroundUpdateHandler(
  525. updater, oneshot=True
  526. )
  527. async def _end_background_update(self, update_name: str) -> None:
  528. """Removes a completed background update task from the queue.
  529. Args:
  530. update_name:: The name of the completed task to remove
  531. Returns:
  532. None, completes once the task is removed.
  533. """
  534. if update_name != self._current_background_update:
  535. raise Exception(
  536. "Cannot end background update %s which isn't currently running"
  537. % update_name
  538. )
  539. self._current_background_update = None
  540. await self.db_pool.simple_delete_one(
  541. "background_updates", keyvalues={"update_name": update_name}
  542. )
  543. async def _background_update_progress(
  544. self, update_name: str, progress: dict
  545. ) -> None:
  546. """Update the progress of a background update
  547. Args:
  548. update_name: The name of the background update task
  549. progress: The progress of the update.
  550. """
  551. await self.db_pool.runInteraction(
  552. "background_update_progress",
  553. self._background_update_progress_txn,
  554. update_name,
  555. progress,
  556. )
  557. def _background_update_progress_txn(
  558. self, txn: "LoggingTransaction", update_name: str, progress: JsonDict
  559. ) -> None:
  560. """Update the progress of a background update
  561. Args:
  562. txn: The transaction.
  563. update_name: The name of the background update task
  564. progress: The progress of the update.
  565. """
  566. progress_json = json_encoder.encode(progress)
  567. self.db_pool.simple_update_one_txn(
  568. txn,
  569. "background_updates",
  570. keyvalues={"update_name": update_name},
  571. updatevalues={"progress_json": progress_json},
  572. )