transaction_manager.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. # Copyright 2019 New Vector 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. import logging
  15. from typing import TYPE_CHECKING, List
  16. from prometheus_client import Gauge
  17. from synapse.api.constants import EduTypes
  18. from synapse.api.errors import HttpResponseException
  19. from synapse.events import EventBase
  20. from synapse.federation.persistence import TransactionActions
  21. from synapse.federation.units import Edu, Transaction
  22. from synapse.logging.opentracing import (
  23. extract_text_map,
  24. set_tag,
  25. start_active_span_follows_from,
  26. tags,
  27. whitelisted_homeserver,
  28. )
  29. from synapse.types import JsonDict
  30. from synapse.util import json_decoder
  31. from synapse.util.metrics import measure_func
  32. if TYPE_CHECKING:
  33. import synapse.server
  34. logger = logging.getLogger(__name__)
  35. issue_8631_logger = logging.getLogger("synapse.8631_debug")
  36. last_pdu_ts_metric = Gauge(
  37. "synapse_federation_last_sent_pdu_time",
  38. "The timestamp of the last PDU which was successfully sent to the given domain",
  39. labelnames=("server_name",),
  40. )
  41. class TransactionManager:
  42. """Helper class which handles building and sending transactions
  43. shared between PerDestinationQueue objects
  44. """
  45. def __init__(self, hs: "synapse.server.HomeServer"):
  46. self._server_name = hs.hostname
  47. self.clock = hs.get_clock() # nb must be called this for @measure_func
  48. self._store = hs.get_datastores().main
  49. self._transaction_actions = TransactionActions(self._store)
  50. self._transport_layer = hs.get_federation_transport_client()
  51. self._federation_metrics_domains = (
  52. hs.config.federation.federation_metrics_domains
  53. )
  54. # HACK to get unique tx id
  55. self._next_txn_id = int(self.clock.time_msec())
  56. @measure_func("_send_new_transaction")
  57. async def send_new_transaction(
  58. self,
  59. destination: str,
  60. pdus: List[EventBase],
  61. edus: List[Edu],
  62. ) -> None:
  63. """
  64. Args:
  65. destination: The destination to send to (e.g. 'example.org')
  66. pdus: In-order list of PDUs to send
  67. edus: List of EDUs to send
  68. """
  69. # Make a transaction-sending opentracing span. This span follows on from
  70. # all the edus in that transaction. This needs to be done since there is
  71. # no active span here, so if the edus were not received by the remote the
  72. # span would have no causality and it would be forgotten.
  73. span_contexts = []
  74. keep_destination = whitelisted_homeserver(destination)
  75. for edu in edus:
  76. context = edu.get_context()
  77. if context:
  78. span_contexts.append(extract_text_map(json_decoder.decode(context)))
  79. if keep_destination:
  80. edu.strip_context()
  81. with start_active_span_follows_from("send_transaction", span_contexts):
  82. logger.debug("TX [%s] _attempt_new_transaction", destination)
  83. txn_id = str(self._next_txn_id)
  84. logger.debug(
  85. "TX [%s] {%s} Attempting new transaction (pdus: %d, edus: %d)",
  86. destination,
  87. txn_id,
  88. len(pdus),
  89. len(edus),
  90. )
  91. transaction = Transaction(
  92. origin_server_ts=int(self.clock.time_msec()),
  93. transaction_id=txn_id,
  94. origin=self._server_name,
  95. destination=destination,
  96. pdus=[p.get_pdu_json() for p in pdus],
  97. edus=[edu.get_dict() for edu in edus],
  98. )
  99. self._next_txn_id += 1
  100. logger.info(
  101. "TX [%s] {%s} Sending transaction [%s], (PDUs: %d, EDUs: %d)",
  102. destination,
  103. txn_id,
  104. transaction.transaction_id,
  105. len(pdus),
  106. len(edus),
  107. )
  108. if issue_8631_logger.isEnabledFor(logging.DEBUG):
  109. DEVICE_UPDATE_EDUS = {
  110. EduTypes.DEVICE_LIST_UPDATE,
  111. EduTypes.SIGNING_KEY_UPDATE,
  112. }
  113. device_list_updates = [
  114. edu.content for edu in edus if edu.edu_type in DEVICE_UPDATE_EDUS
  115. ]
  116. if device_list_updates:
  117. issue_8631_logger.debug(
  118. "about to send txn [%s] including device list updates: %s",
  119. transaction.transaction_id,
  120. device_list_updates,
  121. )
  122. # Actually send the transaction
  123. # FIXME (erikj): This is a bit of a hack to make the Pdu age
  124. # keys work
  125. # FIXME (richardv): I also believe it no longer works. We (now?) store
  126. # "age_ts" in "unsigned" rather than at the top level. See
  127. # https://github.com/matrix-org/synapse/issues/8429.
  128. def json_data_cb() -> JsonDict:
  129. data = transaction.get_dict()
  130. now = int(self.clock.time_msec())
  131. if "pdus" in data:
  132. for p in data["pdus"]:
  133. if "age_ts" in p:
  134. unsigned = p.setdefault("unsigned", {})
  135. unsigned["age"] = now - int(p["age_ts"])
  136. del p["age_ts"]
  137. return data
  138. try:
  139. response = await self._transport_layer.send_transaction(
  140. transaction, json_data_cb
  141. )
  142. except HttpResponseException as e:
  143. code = e.code
  144. set_tag(tags.ERROR, True)
  145. logger.info("TX [%s] {%s} got %d response", destination, txn_id, code)
  146. raise
  147. logger.info("TX [%s] {%s} got 200 response", destination, txn_id)
  148. for e_id, r in response.get("pdus", {}).items():
  149. if "error" in r:
  150. logger.warning(
  151. "TX [%s] {%s} Remote returned error for %s: %s",
  152. destination,
  153. txn_id,
  154. e_id,
  155. r,
  156. )
  157. if pdus and destination in self._federation_metrics_domains:
  158. last_pdu = pdus[-1]
  159. last_pdu_ts_metric.labels(server_name=destination).set(
  160. last_pdu.origin_server_ts / 1000
  161. )