background_updates.py 24 KB

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