background_updates.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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 canonicaljson import json
  17. from twisted.internet import defer
  18. from synapse.metrics.background_process_metrics import run_as_background_process
  19. from . import engines
  20. logger = logging.getLogger(__name__)
  21. class BackgroundUpdatePerformance(object):
  22. """Tracks the how long a background update is taking to update its items"""
  23. def __init__(self, name):
  24. self.name = name
  25. self.total_item_count = 0
  26. self.total_duration_ms = 0
  27. self.avg_item_count = 0
  28. self.avg_duration_ms = 0
  29. def update(self, item_count, duration_ms):
  30. """Update the stats after doing an update"""
  31. self.total_item_count += item_count
  32. self.total_duration_ms += duration_ms
  33. # Exponential moving averages for the number of items updated and
  34. # the duration.
  35. self.avg_item_count += 0.1 * (item_count - self.avg_item_count)
  36. self.avg_duration_ms += 0.1 * (duration_ms - self.avg_duration_ms)
  37. def average_items_per_ms(self):
  38. """An estimate of how long it takes to do a single update.
  39. Returns:
  40. A duration in ms as a float
  41. """
  42. if self.avg_duration_ms == 0:
  43. return 0
  44. elif self.total_item_count == 0:
  45. return None
  46. else:
  47. # Use the exponential moving average so that we can adapt to
  48. # changes in how long the update process takes.
  49. return float(self.avg_item_count) / float(self.avg_duration_ms)
  50. def total_items_per_ms(self):
  51. """An estimate of how long it takes to do a single update.
  52. Returns:
  53. A duration in ms as a float
  54. """
  55. if self.total_duration_ms == 0:
  56. return 0
  57. elif self.total_item_count == 0:
  58. return None
  59. else:
  60. return float(self.total_item_count) / float(self.total_duration_ms)
  61. class BackgroundUpdater(object):
  62. """ Background updates are updates to the database that run in the
  63. background. Each update processes a batch of data at once. We attempt to
  64. limit the impact of each update by monitoring how long each batch takes to
  65. process and autotuning the batch size.
  66. """
  67. MINIMUM_BACKGROUND_BATCH_SIZE = 100
  68. DEFAULT_BACKGROUND_BATCH_SIZE = 100
  69. BACKGROUND_UPDATE_INTERVAL_MS = 1000
  70. BACKGROUND_UPDATE_DURATION_MS = 100
  71. def __init__(self, hs, database):
  72. self._clock = hs.get_clock()
  73. self.db = database
  74. self._background_update_performance = {}
  75. self._background_update_queue = []
  76. self._background_update_handlers = {}
  77. self._all_done = False
  78. def start_doing_background_updates(self):
  79. run_as_background_process("background_updates", self.run_background_updates)
  80. @defer.inlineCallbacks
  81. def run_background_updates(self, sleep=True):
  82. logger.info("Starting background schema updates")
  83. while True:
  84. if sleep:
  85. yield self._clock.sleep(self.BACKGROUND_UPDATE_INTERVAL_MS / 1000.0)
  86. try:
  87. result = yield self.do_next_background_update(
  88. self.BACKGROUND_UPDATE_DURATION_MS
  89. )
  90. except Exception:
  91. logger.exception("Error doing update")
  92. else:
  93. if result is None:
  94. logger.info(
  95. "No more background updates to do."
  96. " Unscheduling background update task."
  97. )
  98. self._all_done = True
  99. return None
  100. @defer.inlineCallbacks
  101. def has_completed_background_updates(self):
  102. """Check if all the background updates have completed
  103. Returns:
  104. Deferred[bool]: 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 have things in our queue, we're not done.
  111. if self._background_update_queue:
  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 = yield 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 in self._background_update_queue:
  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. @defer.inlineCallbacks
  142. def do_next_background_update(self, desired_duration_ms):
  143. """Does some amount of work on the next queued background update
  144. Args:
  145. desired_duration_ms(float): How long we want to spend
  146. updating.
  147. Returns:
  148. A deferred that completes once some amount of work is done.
  149. The deferred will have a value of None if there is currently
  150. no more work to do.
  151. """
  152. if not self._background_update_queue:
  153. updates = yield self.db.simple_select_list(
  154. "background_updates",
  155. keyvalues=None,
  156. retcols=("update_name", "depends_on"),
  157. )
  158. in_flight = set(update["update_name"] for update in updates)
  159. for update in updates:
  160. if update["depends_on"] not in in_flight:
  161. self._background_update_queue.append(update["update_name"])
  162. if not self._background_update_queue:
  163. # no work left to do
  164. return None
  165. # pop from the front, and add back to the back
  166. update_name = self._background_update_queue.pop(0)
  167. self._background_update_queue.append(update_name)
  168. res = yield self._do_background_update(update_name, desired_duration_ms)
  169. return res
  170. @defer.inlineCallbacks
  171. def _do_background_update(self, update_name, desired_duration_ms):
  172. logger.info("Starting update batch on background update '%s'", update_name)
  173. update_handler = self._background_update_handlers[update_name]
  174. performance = self._background_update_performance.get(update_name)
  175. if performance is None:
  176. performance = BackgroundUpdatePerformance(update_name)
  177. self._background_update_performance[update_name] = performance
  178. items_per_ms = performance.average_items_per_ms()
  179. if items_per_ms is not None:
  180. batch_size = int(desired_duration_ms * items_per_ms)
  181. # Clamp the batch size so that we always make progress
  182. batch_size = max(batch_size, self.MINIMUM_BACKGROUND_BATCH_SIZE)
  183. else:
  184. batch_size = self.DEFAULT_BACKGROUND_BATCH_SIZE
  185. progress_json = yield self.db.simple_select_one_onecol(
  186. "background_updates",
  187. keyvalues={"update_name": update_name},
  188. retcol="progress_json",
  189. )
  190. progress = json.loads(progress_json)
  191. time_start = self._clock.time_msec()
  192. items_updated = yield update_handler(progress, batch_size)
  193. time_stop = self._clock.time_msec()
  194. duration_ms = time_stop - time_start
  195. logger.info(
  196. "Running background update %r. Processed %r items in %rms."
  197. " (total_rate=%r/ms, current_rate=%r/ms, total_updated=%r, batch_size=%r)",
  198. update_name,
  199. items_updated,
  200. duration_ms,
  201. performance.total_items_per_ms(),
  202. performance.average_items_per_ms(),
  203. performance.total_item_count,
  204. batch_size,
  205. )
  206. performance.update(items_updated, duration_ms)
  207. return len(self._background_update_performance)
  208. def register_background_update_handler(self, update_name, update_handler):
  209. """Register a handler for doing a background update.
  210. The handler should take two arguments:
  211. * A dict of the current progress
  212. * An integer count of the number of items to update in this batch.
  213. The handler should return a deferred integer count of items updated.
  214. The handler is responsible for updating the progress of the update.
  215. Args:
  216. update_name(str): The name of the update that this code handles.
  217. update_handler(function): The function that does the update.
  218. """
  219. self._background_update_handlers[update_name] = update_handler
  220. def register_noop_background_update(self, update_name):
  221. """Register a noop handler for a background update.
  222. This is useful when we previously did a background update, but no
  223. longer wish to do the update. In this case the background update should
  224. be removed from the schema delta files, but there may still be some
  225. users who have the background update queued, so this method should
  226. also be called to clear the update.
  227. Args:
  228. update_name (str): Name of update
  229. """
  230. @defer.inlineCallbacks
  231. def noop_update(progress, batch_size):
  232. yield self._end_background_update(update_name)
  233. return 1
  234. self.register_background_update_handler(update_name, noop_update)
  235. def register_background_index_update(
  236. self,
  237. update_name,
  238. index_name,
  239. table,
  240. columns,
  241. where_clause=None,
  242. unique=False,
  243. psql_only=False,
  244. ):
  245. """Helper for store classes to do a background index addition
  246. To use:
  247. 1. use a schema delta file to add a background update. Example:
  248. INSERT INTO background_updates (update_name, progress_json) VALUES
  249. ('my_new_index', '{}');
  250. 2. In the Store constructor, call this method
  251. Args:
  252. update_name (str): update_name to register for
  253. index_name (str): name of index to add
  254. table (str): table to add index to
  255. columns (list[str]): columns/expressions to include in index
  256. unique (bool): true to make a UNIQUE index
  257. psql_only: true to only create this index on psql databases (useful
  258. for virtual sqlite tables)
  259. """
  260. def create_index_psql(conn):
  261. conn.rollback()
  262. # postgres insists on autocommit for the index
  263. conn.set_session(autocommit=True)
  264. try:
  265. c = conn.cursor()
  266. # If a previous attempt to create the index was interrupted,
  267. # we may already have a half-built index. Let's just drop it
  268. # before trying to create it again.
  269. sql = "DROP INDEX IF EXISTS %s" % (index_name,)
  270. logger.debug("[SQL] %s", sql)
  271. c.execute(sql)
  272. sql = (
  273. "CREATE %(unique)s INDEX CONCURRENTLY %(name)s"
  274. " ON %(table)s"
  275. " (%(columns)s) %(where_clause)s"
  276. ) % {
  277. "unique": "UNIQUE" if unique else "",
  278. "name": index_name,
  279. "table": table,
  280. "columns": ", ".join(columns),
  281. "where_clause": "WHERE " + where_clause if where_clause else "",
  282. }
  283. logger.debug("[SQL] %s", sql)
  284. c.execute(sql)
  285. finally:
  286. conn.set_session(autocommit=False)
  287. def create_index_sqlite(conn):
  288. # Sqlite doesn't support concurrent creation of indexes.
  289. #
  290. # We don't use partial indices on SQLite as it wasn't introduced
  291. # until 3.8, and wheezy and CentOS 7 have 3.7
  292. #
  293. # We assume that sqlite doesn't give us invalid indices; however
  294. # we may still end up with the index existing but the
  295. # background_updates not having been recorded if synapse got shut
  296. # down at the wrong moment - hance we use IF NOT EXISTS. (SQLite
  297. # has supported CREATE TABLE|INDEX IF NOT EXISTS since 3.3.0.)
  298. sql = (
  299. "CREATE %(unique)s INDEX IF NOT EXISTS %(name)s ON %(table)s"
  300. " (%(columns)s)"
  301. ) % {
  302. "unique": "UNIQUE" if unique else "",
  303. "name": index_name,
  304. "table": table,
  305. "columns": ", ".join(columns),
  306. }
  307. c = conn.cursor()
  308. logger.debug("[SQL] %s", sql)
  309. c.execute(sql)
  310. if isinstance(self.db.engine, engines.PostgresEngine):
  311. runner = create_index_psql
  312. elif psql_only:
  313. runner = None
  314. else:
  315. runner = create_index_sqlite
  316. @defer.inlineCallbacks
  317. def updater(progress, batch_size):
  318. if runner is not None:
  319. logger.info("Adding index %s to %s", index_name, table)
  320. yield self.db.runWithConnection(runner)
  321. yield self._end_background_update(update_name)
  322. return 1
  323. self.register_background_update_handler(update_name, updater)
  324. def start_background_update(self, update_name, progress):
  325. """Starts a background update running.
  326. Args:
  327. update_name: The update to set running.
  328. progress: The initial state of the progress of the update.
  329. Returns:
  330. A deferred that completes once the task has been added to the
  331. queue.
  332. """
  333. # Clear the background update queue so that we will pick up the new
  334. # task on the next iteration of do_background_update.
  335. self._background_update_queue = []
  336. progress_json = json.dumps(progress)
  337. return self.db.simple_insert(
  338. "background_updates",
  339. {"update_name": update_name, "progress_json": progress_json},
  340. )
  341. def _end_background_update(self, update_name):
  342. """Removes a completed background update task from the queue.
  343. Args:
  344. update_name(str): The name of the completed task to remove
  345. Returns:
  346. A deferred that completes once the task is removed.
  347. """
  348. self._background_update_queue = [
  349. name for name in self._background_update_queue if name != update_name
  350. ]
  351. return self.db.simple_delete_one(
  352. "background_updates", keyvalues={"update_name": update_name}
  353. )
  354. def _background_update_progress_txn(self, txn, update_name, progress):
  355. """Update the progress of a background update
  356. Args:
  357. txn(cursor): The transaction.
  358. update_name(str): The name of the background update task
  359. progress(dict): The progress of the update.
  360. """
  361. progress_json = json.dumps(progress)
  362. self.db.simple_update_one_txn(
  363. txn,
  364. "background_updates",
  365. keyvalues={"update_name": update_name},
  366. updatevalues={"progress_json": progress_json},
  367. )