You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

312 lines
11 KiB

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