transaction_queue.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. from twisted.internet import defer
  16. from .persistence import TransactionActions
  17. from .units import Transaction, Edu
  18. from synapse.api.constants import EventTypes, Membership
  19. from synapse.api.errors import HttpResponseException
  20. from synapse.util.async import run_on_reactor
  21. from synapse.util.logcontext import preserve_context_over_fn
  22. from synapse.util.retryutils import (
  23. get_retry_limiter, NotRetryingDestination,
  24. )
  25. from synapse.util.metrics import measure_func
  26. from synapse.types import get_domain_from_id
  27. from synapse.handlers.presence import format_user_presence_state
  28. import synapse.metrics
  29. import logging
  30. logger = logging.getLogger(__name__)
  31. metrics = synapse.metrics.get_metrics_for(__name__)
  32. client_metrics = synapse.metrics.get_metrics_for("synapse.federation.client")
  33. sent_pdus_destination_dist = client_metrics.register_distribution(
  34. "sent_pdu_destinations"
  35. )
  36. sent_edus_counter = client_metrics.register_counter("sent_edus")
  37. class TransactionQueue(object):
  38. """This class makes sure we only have one transaction in flight at
  39. a time for a given destination.
  40. It batches pending PDUs into single transactions.
  41. """
  42. def __init__(self, hs):
  43. self.server_name = hs.hostname
  44. self.store = hs.get_datastore()
  45. self.state = hs.get_state_handler()
  46. self.transaction_actions = TransactionActions(self.store)
  47. self.transport_layer = hs.get_federation_transport_client()
  48. self.clock = hs.get_clock()
  49. # Is a mapping from destinations -> deferreds. Used to keep track
  50. # of which destinations have transactions in flight and when they are
  51. # done
  52. self.pending_transactions = {}
  53. metrics.register_callback(
  54. "pending_destinations",
  55. lambda: len(self.pending_transactions),
  56. )
  57. # Is a mapping from destination -> list of
  58. # tuple(pending pdus, deferred, order)
  59. self.pending_pdus_by_dest = pdus = {}
  60. # destination -> list of tuple(edu, deferred)
  61. self.pending_edus_by_dest = edus = {}
  62. # Presence needs to be separate as we send single aggragate EDUs
  63. self.pending_presence_by_dest = presence = {}
  64. self.pending_edus_keyed_by_dest = edus_keyed = {}
  65. metrics.register_callback(
  66. "pending_pdus",
  67. lambda: sum(map(len, pdus.values())),
  68. )
  69. metrics.register_callback(
  70. "pending_edus",
  71. lambda: (
  72. sum(map(len, edus.values()))
  73. + sum(map(len, presence.values()))
  74. + sum(map(len, edus_keyed.values()))
  75. ),
  76. )
  77. # destination -> list of tuple(failure, deferred)
  78. self.pending_failures_by_dest = {}
  79. self.last_device_stream_id_by_dest = {}
  80. # HACK to get unique tx id
  81. self._next_txn_id = int(self.clock.time_msec())
  82. self._order = 1
  83. self._is_processing = False
  84. self._last_poked_id = -1
  85. def can_send_to(self, destination):
  86. """Can we send messages to the given server?
  87. We can't send messages to ourselves. If we are running on localhost
  88. then we can only federation with other servers running on localhost.
  89. Otherwise we only federate with servers on a public domain.
  90. Args:
  91. destination(str): The server we are possibly trying to send to.
  92. Returns:
  93. bool: True if we can send to the server.
  94. """
  95. if destination == self.server_name:
  96. return False
  97. if self.server_name.startswith("localhost"):
  98. return destination.startswith("localhost")
  99. else:
  100. return not destination.startswith("localhost")
  101. @defer.inlineCallbacks
  102. def notify_new_events(self, current_id):
  103. """This gets called when we have some new events we might want to
  104. send out to other servers.
  105. """
  106. self._last_poked_id = max(current_id, self._last_poked_id)
  107. if self._is_processing:
  108. return
  109. try:
  110. self._is_processing = True
  111. while True:
  112. last_token = yield self.store.get_federation_out_pos("events")
  113. next_token, events = yield self.store.get_all_new_events_stream(
  114. last_token, self._last_poked_id, limit=20,
  115. )
  116. logger.debug("Handling %s -> %s", last_token, next_token)
  117. if not events and next_token >= self._last_poked_id:
  118. break
  119. for event in events:
  120. users_in_room = yield self.state.get_current_user_in_room(
  121. event.room_id, latest_event_ids=[event.event_id],
  122. )
  123. destinations = set(
  124. get_domain_from_id(user_id) for user_id in users_in_room
  125. )
  126. if event.type == EventTypes.Member:
  127. if event.content["membership"] == Membership.JOIN:
  128. destinations.add(get_domain_from_id(event.state_key))
  129. logger.debug("Sending %s to %r", event, destinations)
  130. self._send_pdu(event, destinations)
  131. yield self.store.update_federation_out_pos(
  132. "events", next_token
  133. )
  134. finally:
  135. self._is_processing = False
  136. def _send_pdu(self, pdu, destinations):
  137. # We loop through all destinations to see whether we already have
  138. # a transaction in progress. If we do, stick it in the pending_pdus
  139. # table and we'll get back to it later.
  140. order = self._order
  141. self._order += 1
  142. destinations = set(destinations)
  143. destinations = set(
  144. dest for dest in destinations if self.can_send_to(dest)
  145. )
  146. logger.debug("Sending to: %s", str(destinations))
  147. if not destinations:
  148. return
  149. sent_pdus_destination_dist.inc_by(len(destinations))
  150. for destination in destinations:
  151. self.pending_pdus_by_dest.setdefault(destination, []).append(
  152. (pdu, order)
  153. )
  154. preserve_context_over_fn(
  155. self._attempt_new_transaction, destination
  156. )
  157. def send_presence(self, destination, states):
  158. if not self.can_send_to(destination):
  159. return
  160. self.pending_presence_by_dest.setdefault(destination, {}).update({
  161. state.user_id: state for state in states
  162. })
  163. preserve_context_over_fn(
  164. self._attempt_new_transaction, destination
  165. )
  166. def send_edu(self, destination, edu_type, content, key=None):
  167. edu = Edu(
  168. origin=self.server_name,
  169. destination=destination,
  170. edu_type=edu_type,
  171. content=content,
  172. )
  173. if not self.can_send_to(destination):
  174. return
  175. sent_edus_counter.inc()
  176. if key:
  177. self.pending_edus_keyed_by_dest.setdefault(
  178. destination, {}
  179. )[(edu.edu_type, key)] = edu
  180. else:
  181. self.pending_edus_by_dest.setdefault(destination, []).append(edu)
  182. preserve_context_over_fn(
  183. self._attempt_new_transaction, destination
  184. )
  185. def send_failure(self, failure, destination):
  186. if destination == self.server_name or destination == "localhost":
  187. return
  188. if not self.can_send_to(destination):
  189. return
  190. self.pending_failures_by_dest.setdefault(
  191. destination, []
  192. ).append(failure)
  193. preserve_context_over_fn(
  194. self._attempt_new_transaction, destination
  195. )
  196. def send_device_messages(self, destination):
  197. if destination == self.server_name or destination == "localhost":
  198. return
  199. if not self.can_send_to(destination):
  200. return
  201. preserve_context_over_fn(
  202. self._attempt_new_transaction, destination
  203. )
  204. def get_current_token(self):
  205. return 0
  206. @defer.inlineCallbacks
  207. def _attempt_new_transaction(self, destination):
  208. # list of (pending_pdu, deferred, order)
  209. if destination in self.pending_transactions:
  210. # XXX: pending_transactions can get stuck on by a never-ending
  211. # request at which point pending_pdus_by_dest just keeps growing.
  212. # we need application-layer timeouts of some flavour of these
  213. # requests
  214. logger.debug(
  215. "TX [%s] Transaction already in progress",
  216. destination
  217. )
  218. return
  219. try:
  220. self.pending_transactions[destination] = 1
  221. yield run_on_reactor()
  222. while True:
  223. pending_pdus = self.pending_pdus_by_dest.pop(destination, [])
  224. pending_edus = self.pending_edus_by_dest.pop(destination, [])
  225. pending_presence = self.pending_presence_by_dest.pop(destination, {})
  226. pending_failures = self.pending_failures_by_dest.pop(destination, [])
  227. pending_edus.extend(
  228. self.pending_edus_keyed_by_dest.pop(destination, {}).values()
  229. )
  230. limiter = yield get_retry_limiter(
  231. destination,
  232. self.clock,
  233. self.store,
  234. )
  235. device_message_edus, device_stream_id = (
  236. yield self._get_new_device_messages(destination)
  237. )
  238. pending_edus.extend(device_message_edus)
  239. if pending_presence:
  240. pending_edus.append(
  241. Edu(
  242. origin=self.server_name,
  243. destination=destination,
  244. edu_type="m.presence",
  245. content={
  246. "push": [
  247. format_user_presence_state(
  248. presence, self.clock.time_msec()
  249. )
  250. for presence in pending_presence.values()
  251. ]
  252. },
  253. )
  254. )
  255. if pending_pdus:
  256. logger.debug("TX [%s] len(pending_pdus_by_dest[dest]) = %d",
  257. destination, len(pending_pdus))
  258. if not pending_pdus and not pending_edus and not pending_failures:
  259. logger.debug("TX [%s] Nothing to send", destination)
  260. self.last_device_stream_id_by_dest[destination] = (
  261. device_stream_id
  262. )
  263. return
  264. success = yield self._send_new_transaction(
  265. destination, pending_pdus, pending_edus, pending_failures,
  266. device_stream_id,
  267. should_delete_from_device_stream=bool(device_message_edus),
  268. limiter=limiter,
  269. )
  270. if not success:
  271. break
  272. except NotRetryingDestination:
  273. logger.info(
  274. "TX [%s] not ready for retry yet - "
  275. "dropping transaction for now",
  276. destination,
  277. )
  278. finally:
  279. # We want to be *very* sure we delete this after we stop processing
  280. self.pending_transactions.pop(destination, None)
  281. @defer.inlineCallbacks
  282. def _get_new_device_messages(self, destination):
  283. last_device_stream_id = self.last_device_stream_id_by_dest.get(destination, 0)
  284. to_device_stream_id = self.store.get_to_device_stream_token()
  285. contents, stream_id = yield self.store.get_new_device_msgs_for_remote(
  286. destination, last_device_stream_id, to_device_stream_id
  287. )
  288. edus = [
  289. Edu(
  290. origin=self.server_name,
  291. destination=destination,
  292. edu_type="m.direct_to_device",
  293. content=content,
  294. )
  295. for content in contents
  296. ]
  297. defer.returnValue((edus, stream_id))
  298. @measure_func("_send_new_transaction")
  299. @defer.inlineCallbacks
  300. def _send_new_transaction(self, destination, pending_pdus, pending_edus,
  301. pending_failures, device_stream_id,
  302. should_delete_from_device_stream, limiter):
  303. # Sort based on the order field
  304. pending_pdus.sort(key=lambda t: t[1])
  305. pdus = [x[0] for x in pending_pdus]
  306. edus = pending_edus
  307. failures = [x.get_dict() for x in pending_failures]
  308. success = True
  309. try:
  310. logger.debug("TX [%s] _attempt_new_transaction", destination)
  311. txn_id = str(self._next_txn_id)
  312. logger.debug(
  313. "TX [%s] {%s} Attempting new transaction"
  314. " (pdus: %d, edus: %d, failures: %d)",
  315. destination, txn_id,
  316. len(pdus),
  317. len(edus),
  318. len(failures)
  319. )
  320. logger.debug("TX [%s] Persisting transaction...", destination)
  321. transaction = Transaction.create_new(
  322. origin_server_ts=int(self.clock.time_msec()),
  323. transaction_id=txn_id,
  324. origin=self.server_name,
  325. destination=destination,
  326. pdus=pdus,
  327. edus=edus,
  328. pdu_failures=failures,
  329. )
  330. self._next_txn_id += 1
  331. yield self.transaction_actions.prepare_to_send(transaction)
  332. logger.debug("TX [%s] Persisted transaction", destination)
  333. logger.info(
  334. "TX [%s] {%s} Sending transaction [%s],"
  335. " (PDUs: %d, EDUs: %d, failures: %d)",
  336. destination, txn_id,
  337. transaction.transaction_id,
  338. len(pdus),
  339. len(edus),
  340. len(failures),
  341. )
  342. with limiter:
  343. # Actually send the transaction
  344. # FIXME (erikj): This is a bit of a hack to make the Pdu age
  345. # keys work
  346. def json_data_cb():
  347. data = transaction.get_dict()
  348. now = int(self.clock.time_msec())
  349. if "pdus" in data:
  350. for p in data["pdus"]:
  351. if "age_ts" in p:
  352. unsigned = p.setdefault("unsigned", {})
  353. unsigned["age"] = now - int(p["age_ts"])
  354. del p["age_ts"]
  355. return data
  356. try:
  357. response = yield self.transport_layer.send_transaction(
  358. transaction, json_data_cb
  359. )
  360. code = 200
  361. if response:
  362. for e_id, r in response.get("pdus", {}).items():
  363. if "error" in r:
  364. logger.warn(
  365. "Transaction returned error for %s: %s",
  366. e_id, r,
  367. )
  368. except HttpResponseException as e:
  369. code = e.code
  370. response = e.response
  371. logger.info(
  372. "TX [%s] {%s} got %d response",
  373. destination, txn_id, code
  374. )
  375. logger.debug("TX [%s] Sent transaction", destination)
  376. logger.debug("TX [%s] Marking as delivered...", destination)
  377. yield self.transaction_actions.delivered(
  378. transaction, code, response
  379. )
  380. logger.debug("TX [%s] Marked as delivered", destination)
  381. if code != 200:
  382. for p in pdus:
  383. logger.info(
  384. "Failed to send event %s to %s", p.event_id, destination
  385. )
  386. success = False
  387. else:
  388. # Remove the acknowledged device messages from the database
  389. if should_delete_from_device_stream:
  390. yield self.store.delete_device_msgs_for_remote(
  391. destination, device_stream_id
  392. )
  393. self.last_device_stream_id_by_dest[destination] = device_stream_id
  394. except RuntimeError as e:
  395. # We capture this here as there as nothing actually listens
  396. # for this finishing functions deferred.
  397. logger.warn(
  398. "TX [%s] Problem in _attempt_transaction: %s",
  399. destination,
  400. e,
  401. )
  402. success = False
  403. for p in pdus:
  404. logger.info("Failed to send event %s to %s", p.event_id, destination)
  405. except Exception as e:
  406. # We capture this here as there as nothing actually listens
  407. # for this finishing functions deferred.
  408. logger.warn(
  409. "TX [%s] Problem in _attempt_transaction: %s",
  410. destination,
  411. e,
  412. )
  413. success = False
  414. for p in pdus:
  415. logger.info("Failed to send event %s to %s", p.event_id, destination)
  416. defer.returnValue(success)