background_updates.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import Optional
  17. from canonicaljson import json
  18. from twisted.internet import defer
  19. from synapse.metrics.background_process_metrics import run_as_background_process
  20. from . import engines
  21. logger = logging.getLogger(__name__)
  22. class BackgroundUpdatePerformance(object):
  23. """Tracks the how long a background update is taking to update its items"""
  24. def __init__(self, name):
  25. self.name = name
  26. self.total_item_count = 0
  27. self.total_duration_ms = 0
  28. self.avg_item_count = 0
  29. self.avg_duration_ms = 0
  30. def update(self, item_count, duration_ms):
  31. """Update the stats after doing an update"""
  32. self.total_item_count += item_count
  33. self.total_duration_ms += duration_ms
  34. # Exponential moving averages for the number of items updated and
  35. # the duration.
  36. self.avg_item_count += 0.1 * (item_count - self.avg_item_count)
  37. self.avg_duration_ms += 0.1 * (duration_ms - self.avg_duration_ms)
  38. def average_items_per_ms(self):
  39. """An estimate of how long it takes to do a single update.
  40. Returns:
  41. A duration in ms as a float
  42. """
  43. if self.avg_duration_ms == 0:
  44. return 0
  45. elif self.total_item_count == 0:
  46. return None
  47. else:
  48. # Use the exponential moving average so that we can adapt to
  49. # changes in how long the update process takes.
  50. return float(self.avg_item_count) / float(self.avg_duration_ms)
  51. def total_items_per_ms(self):
  52. """An estimate of how long it takes to do a single update.
  53. Returns:
  54. A duration in ms as a float
  55. """
  56. if self.total_duration_ms == 0:
  57. return 0
  58. elif self.total_item_count == 0:
  59. return None
  60. else:
  61. return float(self.total_item_count) / float(self.total_duration_ms)
  62. class BackgroundUpdater(object):
  63. """ Background updates are updates to the database that run in the
  64. background. Each update processes a batch of data at once. We attempt to
  65. limit the impact of each update by monitoring how long each batch takes to
  66. process and autotuning the batch size.
  67. """
  68. MINIMUM_BACKGROUND_BATCH_SIZE = 100
  69. DEFAULT_BACKGROUND_BATCH_SIZE = 100
  70. BACKGROUND_UPDATE_INTERVAL_MS = 1000
  71. BACKGROUND_UPDATE_DURATION_MS = 100
  72. def __init__(self, hs, database):
  73. self._clock = hs.get_clock()
  74. self.db = database
  75. # if a background update is currently running, its name.
  76. self._current_background_update = None # type: Optional[str]
  77. self._background_update_performance = {}
  78. self._background_update_handlers = {}
  79. self._all_done = False
  80. def start_doing_background_updates(self):
  81. run_as_background_process("background_updates", self.run_background_updates)
  82. async def run_background_updates(self, sleep=True):
  83. logger.info("Starting background schema updates")
  84. while True:
  85. if sleep:
  86. await self._clock.sleep(self.BACKGROUND_UPDATE_INTERVAL_MS / 1000.0)
  87. try:
  88. result = await self.do_next_background_update(
  89. self.BACKGROUND_UPDATE_DURATION_MS
  90. )
  91. except Exception:
  92. logger.exception("Error doing update")
  93. else:
  94. if result:
  95. logger.info(
  96. "No more background updates to do."
  97. " Unscheduling background update task."
  98. )
  99. self._all_done = True
  100. return None
  101. async def has_completed_background_updates(self) -> bool:
  102. """Check if all the background updates have completed
  103. Returns:
  104. True if all background updates have completed
  105. """
  106. # if we've previously determined that there is nothing left to do, that
  107. # is easy
  108. if self._all_done:
  109. return True
  110. # obviously, if we are currently processing an update, we're not done.
  111. if self._current_background_update:
  112. return False
  113. # otherwise, check if there are updates to be run. This is important,
  114. # as we may be running on a worker which doesn't perform the bg updates
  115. # itself, but still wants to wait for them to happen.
  116. updates = await self.db.simple_select_onecol(
  117. "background_updates",
  118. keyvalues=None,
  119. retcol="1",
  120. desc="has_completed_background_updates",
  121. )
  122. if not updates:
  123. self._all_done = True
  124. return True
  125. return False
  126. async def has_completed_background_update(self, update_name) -> bool:
  127. """Check if the given background update has finished running.
  128. """
  129. if self._all_done:
  130. return True
  131. if update_name == self._current_background_update:
  132. return False
  133. update_exists = await self.db.simple_select_one_onecol(
  134. "background_updates",
  135. keyvalues={"update_name": update_name},
  136. retcol="1",
  137. desc="has_completed_background_update",
  138. allow_none=True,
  139. )
  140. return not update_exists
  141. async def do_next_background_update(self, desired_duration_ms: float) -> bool:
  142. """Does some amount of work on the next queued background update
  143. Returns once some amount of work is done.
  144. Args:
  145. desired_duration_ms(float): How long we want to spend
  146. updating.
  147. Returns:
  148. True if we have finished running all the background updates, otherwise False
  149. """
  150. def get_background_updates_txn(txn):
  151. txn.execute(
  152. """
  153. SELECT update_name, depends_on FROM background_updates
  154. ORDER BY ordering, update_name
  155. """
  156. )
  157. return self.db.cursor_to_dict(txn)
  158. if not self._current_background_update:
  159. all_pending_updates = await self.db.runInteraction(
  160. "background_updates", get_background_updates_txn,
  161. )
  162. if not all_pending_updates:
  163. # no work left to do
  164. return True
  165. # find the first update which isn't dependent on another one in the queue.
  166. pending = {update["update_name"] for update in all_pending_updates}
  167. for upd in all_pending_updates:
  168. depends_on = upd["depends_on"]
  169. if not depends_on or depends_on not in pending:
  170. break
  171. logger.info(
  172. "Not starting on bg update %s until %s is done",
  173. upd["update_name"],
  174. depends_on,
  175. )
  176. else:
  177. # if we get to the end of that for loop, there is a problem
  178. raise Exception(
  179. "Unable to find a background update which doesn't depend on "
  180. "another: dependency cycle?"
  181. )
  182. self._current_background_update = upd["update_name"]
  183. await self._do_background_update(desired_duration_ms)
  184. return False
  185. async def _do_background_update(self, desired_duration_ms: float) -> int:
  186. update_name = self._current_background_update
  187. logger.info("Starting update batch on background update '%s'", update_name)
  188. update_handler = self._background_update_handlers[update_name]
  189. performance = self._background_update_performance.get(update_name)
  190. if performance is None:
  191. performance = BackgroundUpdatePerformance(update_name)
  192. self._background_update_performance[update_name] = performance
  193. items_per_ms = performance.average_items_per_ms()
  194. if items_per_ms is not None:
  195. batch_size = int(desired_duration_ms * items_per_ms)
  196. # Clamp the batch size so that we always make progress
  197. batch_size = max(batch_size, self.MINIMUM_BACKGROUND_BATCH_SIZE)
  198. else:
  199. batch_size = self.DEFAULT_BACKGROUND_BATCH_SIZE
  200. progress_json = await self.db.simple_select_one_onecol(
  201. "background_updates",
  202. keyvalues={"update_name": update_name},
  203. retcol="progress_json",
  204. )
  205. progress = json.loads(progress_json)
  206. time_start = self._clock.time_msec()
  207. items_updated = await update_handler(progress, batch_size)
  208. time_stop = self._clock.time_msec()
  209. duration_ms = time_stop - time_start
  210. logger.info(
  211. "Running background update %r. Processed %r items in %rms."
  212. " (total_rate=%r/ms, current_rate=%r/ms, total_updated=%r, batch_size=%r)",
  213. update_name,
  214. items_updated,
  215. duration_ms,
  216. performance.total_items_per_ms(),
  217. performance.average_items_per_ms(),
  218. performance.total_item_count,
  219. batch_size,
  220. )
  221. performance.update(items_updated, duration_ms)
  222. return len(self._background_update_performance)
  223. def register_background_update_handler(self, update_name, update_handler):
  224. """Register a handler for doing a background update.
  225. The handler should take two arguments:
  226. * A dict of the current progress
  227. * An integer count of the number of items to update in this batch.
  228. The handler should return a deferred or coroutine which returns an integer count
  229. of items updated.
  230. The handler is responsible for updating the progress of the update.
  231. Args:
  232. update_name(str): The name of the update that this code handles.
  233. update_handler(function): The function that does the update.
  234. """
  235. self._background_update_handlers[update_name] = update_handler
  236. def register_noop_background_update(self, update_name):
  237. """Register a noop handler for a background update.
  238. This is useful when we previously did a background update, but no
  239. longer wish to do the update. In this case the background update should
  240. be removed from the schema delta files, but there may still be some
  241. users who have the background update queued, so this method should
  242. also be called to clear the update.
  243. Args:
  244. update_name (str): Name of update
  245. """
  246. @defer.inlineCallbacks
  247. def noop_update(progress, batch_size):
  248. yield self._end_background_update(update_name)
  249. return 1
  250. self.register_background_update_handler(update_name, noop_update)
  251. def register_background_index_update(
  252. self,
  253. update_name,
  254. index_name,
  255. table,
  256. columns,
  257. where_clause=None,
  258. unique=False,
  259. psql_only=False,
  260. ):
  261. """Helper for store classes to do a background index addition
  262. To use:
  263. 1. use a schema delta file to add a background update. Example:
  264. INSERT INTO background_updates (update_name, progress_json) VALUES
  265. ('my_new_index', '{}');
  266. 2. In the Store constructor, call this method
  267. Args:
  268. update_name (str): update_name to register for
  269. index_name (str): name of index to add
  270. table (str): table to add index to
  271. columns (list[str]): columns/expressions to include in index
  272. unique (bool): true to make a UNIQUE index
  273. psql_only: true to only create this index on psql databases (useful
  274. for virtual sqlite tables)
  275. """
  276. def create_index_psql(conn):
  277. conn.rollback()
  278. # postgres insists on autocommit for the index
  279. conn.set_session(autocommit=True)
  280. try:
  281. c = conn.cursor()
  282. # If a previous attempt to create the index was interrupted,
  283. # we may already have a half-built index. Let's just drop it
  284. # before trying to create it again.
  285. sql = "DROP INDEX IF EXISTS %s" % (index_name,)
  286. logger.debug("[SQL] %s", sql)
  287. c.execute(sql)
  288. sql = (
  289. "CREATE %(unique)s INDEX CONCURRENTLY %(name)s"
  290. " ON %(table)s"
  291. " (%(columns)s) %(where_clause)s"
  292. ) % {
  293. "unique": "UNIQUE" if unique else "",
  294. "name": index_name,
  295. "table": table,
  296. "columns": ", ".join(columns),
  297. "where_clause": "WHERE " + where_clause if where_clause else "",
  298. }
  299. logger.debug("[SQL] %s", sql)
  300. c.execute(sql)
  301. finally:
  302. conn.set_session(autocommit=False)
  303. def create_index_sqlite(conn):
  304. # Sqlite doesn't support concurrent creation of indexes.
  305. #
  306. # We don't use partial indices on SQLite as it wasn't introduced
  307. # until 3.8, and wheezy and CentOS 7 have 3.7
  308. #
  309. # We assume that sqlite doesn't give us invalid indices; however
  310. # we may still end up with the index existing but the
  311. # background_updates not having been recorded if synapse got shut
  312. # down at the wrong moment - hance we use IF NOT EXISTS. (SQLite
  313. # has supported CREATE TABLE|INDEX IF NOT EXISTS since 3.3.0.)
  314. sql = (
  315. "CREATE %(unique)s INDEX IF NOT EXISTS %(name)s ON %(table)s"
  316. " (%(columns)s)"
  317. ) % {
  318. "unique": "UNIQUE" if unique else "",
  319. "name": index_name,
  320. "table": table,
  321. "columns": ", ".join(columns),
  322. }
  323. c = conn.cursor()
  324. logger.debug("[SQL] %s", sql)
  325. c.execute(sql)
  326. if isinstance(self.db.engine, engines.PostgresEngine):
  327. runner = create_index_psql
  328. elif psql_only:
  329. runner = None
  330. else:
  331. runner = create_index_sqlite
  332. @defer.inlineCallbacks
  333. def updater(progress, batch_size):
  334. if runner is not None:
  335. logger.info("Adding index %s to %s", index_name, table)
  336. yield self.db.runWithConnection(runner)
  337. yield self._end_background_update(update_name)
  338. return 1
  339. self.register_background_update_handler(update_name, updater)
  340. def _end_background_update(self, update_name):
  341. """Removes a completed background update task from the queue.
  342. Args:
  343. update_name(str): The name of the completed task to remove
  344. Returns:
  345. A deferred that completes once the task is removed.
  346. """
  347. if update_name != self._current_background_update:
  348. raise Exception(
  349. "Cannot end background update %s which isn't currently running"
  350. % update_name
  351. )
  352. self._current_background_update = None
  353. return self.db.simple_delete_one(
  354. "background_updates", keyvalues={"update_name": update_name}
  355. )
  356. def _background_update_progress(self, update_name: str, progress: dict):
  357. """Update the progress of a background update
  358. Args:
  359. update_name: The name of the background update task
  360. progress: The progress of the update.
  361. """
  362. return self.db.runInteraction(
  363. "background_update_progress",
  364. self._background_update_progress_txn,
  365. update_name,
  366. progress,
  367. )
  368. def _background_update_progress_txn(self, txn, update_name, progress):
  369. """Update the progress of a background update
  370. Args:
  371. txn(cursor): The transaction.
  372. update_name(str): The name of the background update task
  373. progress(dict): The progress of the update.
  374. """
  375. progress_json = json.dumps(progress)
  376. self.db.simple_update_one_txn(
  377. txn,
  378. "background_updates",
  379. keyvalues={"update_name": update_name},
  380. updatevalues={"progress_json": progress_json},
  381. )