scheduler.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 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. """
  16. This module controls the reliability for application service transactions.
  17. The nominal flow through this module looks like:
  18. __________
  19. 1---ASa[e]-->| Service |--> Queue ASa[f]
  20. 2----ASb[e]->| Queuer |
  21. 3--ASa[f]--->|__________|-----------+ ASa[e], ASb[e]
  22. V
  23. -````````- +------------+
  24. |````````|<--StoreTxn-|Transaction |
  25. |Database| | Controller |---> SEND TO AS
  26. `--------` +------------+
  27. What happens on SEND TO AS depends on the state of the Application Service:
  28. - If the AS is marked as DOWN, do nothing.
  29. - If the AS is marked as UP, send the transaction.
  30. * SUCCESS : Increment where the AS is up to txn-wise and nuke the txn
  31. contents from the db.
  32. * FAILURE : Marked AS as DOWN and start Recoverer.
  33. Recoverer attempts to recover ASes who have died. The flow for this looks like:
  34. ,--------------------- backoff++ --------------.
  35. V |
  36. START ---> Wait exp ------> Get oldest txn ID from ----> FAILURE
  37. backoff DB and try to send it
  38. ^ |___________
  39. Mark AS as | V
  40. UP & quit +---------- YES SUCCESS
  41. | | |
  42. NO <--- Have more txns? <------ Mark txn success & nuke <-+
  43. from db; incr AS pos.
  44. Reset backoff.
  45. This is all tied together by the AppServiceScheduler which DIs the required
  46. components.
  47. """
  48. import logging
  49. from typing import List
  50. from synapse.appservice import ApplicationService, ApplicationServiceState
  51. from synapse.events import EventBase
  52. from synapse.logging.context import run_in_background
  53. from synapse.metrics.background_process_metrics import run_as_background_process
  54. from synapse.types import JsonDict
  55. logger = logging.getLogger(__name__)
  56. # Maximum number of events to provide in an AS transaction.
  57. MAX_PERSISTENT_EVENTS_PER_TRANSACTION = 100
  58. # Maximum number of ephemeral events to provide in an AS transaction.
  59. MAX_EPHEMERAL_EVENTS_PER_TRANSACTION = 100
  60. class ApplicationServiceScheduler:
  61. """ Public facing API for this module. Does the required DI to tie the
  62. components together. This also serves as the "event_pool", which in this
  63. case is a simple array.
  64. """
  65. def __init__(self, hs):
  66. self.clock = hs.get_clock()
  67. self.store = hs.get_datastore()
  68. self.as_api = hs.get_application_service_api()
  69. self.txn_ctrl = _TransactionController(self.clock, self.store, self.as_api)
  70. self.queuer = _ServiceQueuer(self.txn_ctrl, self.clock)
  71. async def start(self):
  72. logger.info("Starting appservice scheduler")
  73. # check for any DOWN ASes and start recoverers for them.
  74. services = await self.store.get_appservices_by_state(
  75. ApplicationServiceState.DOWN
  76. )
  77. for service in services:
  78. self.txn_ctrl.start_recoverer(service)
  79. def submit_event_for_as(self, service: ApplicationService, event: EventBase):
  80. self.queuer.enqueue_event(service, event)
  81. def submit_ephemeral_events_for_as(
  82. self, service: ApplicationService, events: List[JsonDict]
  83. ):
  84. self.queuer.enqueue_ephemeral(service, events)
  85. class _ServiceQueuer:
  86. """Queue of events waiting to be sent to appservices.
  87. Groups events into transactions per-appservice, and sends them on to the
  88. TransactionController. Makes sure that we only have one transaction in flight per
  89. appservice at a given time.
  90. """
  91. def __init__(self, txn_ctrl, clock):
  92. self.queued_events = {} # dict of {service_id: [events]}
  93. self.queued_ephemeral = {} # dict of {service_id: [events]}
  94. # the appservices which currently have a transaction in flight
  95. self.requests_in_flight = set()
  96. self.txn_ctrl = txn_ctrl
  97. self.clock = clock
  98. def _start_background_request(self, service):
  99. # start a sender for this appservice if we don't already have one
  100. if service.id in self.requests_in_flight:
  101. return
  102. run_as_background_process(
  103. "as-sender-%s" % (service.id,), self._send_request, service
  104. )
  105. def enqueue_event(self, service: ApplicationService, event: EventBase):
  106. self.queued_events.setdefault(service.id, []).append(event)
  107. self._start_background_request(service)
  108. def enqueue_ephemeral(self, service: ApplicationService, events: List[JsonDict]):
  109. self.queued_ephemeral.setdefault(service.id, []).extend(events)
  110. self._start_background_request(service)
  111. async def _send_request(self, service: ApplicationService):
  112. # sanity-check: we shouldn't get here if this service already has a sender
  113. # running.
  114. assert service.id not in self.requests_in_flight
  115. self.requests_in_flight.add(service.id)
  116. try:
  117. while True:
  118. all_events = self.queued_events.get(service.id, [])
  119. events = all_events[:MAX_PERSISTENT_EVENTS_PER_TRANSACTION]
  120. del all_events[:MAX_PERSISTENT_EVENTS_PER_TRANSACTION]
  121. all_events_ephemeral = self.queued_ephemeral.get(service.id, [])
  122. ephemeral = all_events_ephemeral[:MAX_EPHEMERAL_EVENTS_PER_TRANSACTION]
  123. del all_events_ephemeral[:MAX_EPHEMERAL_EVENTS_PER_TRANSACTION]
  124. if not events and not ephemeral:
  125. return
  126. try:
  127. await self.txn_ctrl.send(service, events, ephemeral)
  128. except Exception:
  129. logger.exception("AS request failed")
  130. finally:
  131. self.requests_in_flight.discard(service.id)
  132. class _TransactionController:
  133. """Transaction manager.
  134. Builds AppServiceTransactions and runs their lifecycle. Also starts a Recoverer
  135. if a transaction fails.
  136. (Note we have only have one of these in the homeserver.)
  137. Args:
  138. clock (synapse.util.Clock):
  139. store (synapse.storage.DataStore):
  140. as_api (synapse.appservice.api.ApplicationServiceApi):
  141. """
  142. def __init__(self, clock, store, as_api):
  143. self.clock = clock
  144. self.store = store
  145. self.as_api = as_api
  146. # map from service id to recoverer instance
  147. self.recoverers = {}
  148. # for UTs
  149. self.RECOVERER_CLASS = _Recoverer
  150. async def send(
  151. self,
  152. service: ApplicationService,
  153. events: List[EventBase],
  154. ephemeral: List[JsonDict] = [],
  155. ):
  156. try:
  157. txn = await self.store.create_appservice_txn(
  158. service=service, events=events, ephemeral=ephemeral
  159. )
  160. service_is_up = await self._is_service_up(service)
  161. if service_is_up:
  162. sent = await txn.send(self.as_api)
  163. if sent:
  164. await txn.complete(self.store)
  165. else:
  166. run_in_background(self._on_txn_fail, service)
  167. except Exception:
  168. logger.exception("Error creating appservice transaction")
  169. run_in_background(self._on_txn_fail, service)
  170. async def on_recovered(self, recoverer):
  171. logger.info(
  172. "Successfully recovered application service AS ID %s", recoverer.service.id
  173. )
  174. self.recoverers.pop(recoverer.service.id)
  175. logger.info("Remaining active recoverers: %s", len(self.recoverers))
  176. await self.store.set_appservice_state(
  177. recoverer.service, ApplicationServiceState.UP
  178. )
  179. async def _on_txn_fail(self, service):
  180. try:
  181. await self.store.set_appservice_state(service, ApplicationServiceState.DOWN)
  182. self.start_recoverer(service)
  183. except Exception:
  184. logger.exception("Error starting AS recoverer")
  185. def start_recoverer(self, service):
  186. """Start a Recoverer for the given service
  187. Args:
  188. service (synapse.appservice.ApplicationService):
  189. """
  190. logger.info("Starting recoverer for AS ID %s", service.id)
  191. assert service.id not in self.recoverers
  192. recoverer = self.RECOVERER_CLASS(
  193. self.clock, self.store, self.as_api, service, self.on_recovered
  194. )
  195. self.recoverers[service.id] = recoverer
  196. recoverer.recover()
  197. logger.info("Now %i active recoverers", len(self.recoverers))
  198. async def _is_service_up(self, service: ApplicationService) -> bool:
  199. state = await self.store.get_appservice_state(service)
  200. return state == ApplicationServiceState.UP or state is None
  201. class _Recoverer:
  202. """Manages retries and backoff for a DOWN appservice.
  203. We have one of these for each appservice which is currently considered DOWN.
  204. Args:
  205. clock (synapse.util.Clock):
  206. store (synapse.storage.DataStore):
  207. as_api (synapse.appservice.api.ApplicationServiceApi):
  208. service (synapse.appservice.ApplicationService): the service we are managing
  209. callback (callable[_Recoverer]): called once the service recovers.
  210. """
  211. def __init__(self, clock, store, as_api, service, callback):
  212. self.clock = clock
  213. self.store = store
  214. self.as_api = as_api
  215. self.service = service
  216. self.callback = callback
  217. self.backoff_counter = 1
  218. def recover(self):
  219. def _retry():
  220. run_as_background_process(
  221. "as-recoverer-%s" % (self.service.id,), self.retry
  222. )
  223. delay = 2 ** self.backoff_counter
  224. logger.info("Scheduling retries on %s in %fs", self.service.id, delay)
  225. self.clock.call_later(delay, _retry)
  226. def _backoff(self):
  227. # cap the backoff to be around 8.5min => (2^9) = 512 secs
  228. if self.backoff_counter < 9:
  229. self.backoff_counter += 1
  230. self.recover()
  231. async def retry(self):
  232. logger.info("Starting retries on %s", self.service.id)
  233. try:
  234. while True:
  235. txn = await self.store.get_oldest_unsent_txn(self.service)
  236. if not txn:
  237. # nothing left: we're done!
  238. await self.callback(self)
  239. return
  240. logger.info(
  241. "Retrying transaction %s for AS ID %s", txn.id, txn.service.id
  242. )
  243. sent = await txn.send(self.as_api)
  244. if not sent:
  245. break
  246. await txn.complete(self.store)
  247. # reset the backoff counter and then process the next transaction
  248. self.backoff_counter = 1
  249. except Exception:
  250. logger.exception("Unexpected error running retries")
  251. # we didn't manage to send all of the transactions before we got an error of
  252. # some flavour: reschedule the next retry.
  253. self._backoff()