client.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. # Copyright 2017 Vector Creations 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. """A replication client for use by synapse workers.
  15. """
  16. import logging
  17. from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Set, Tuple
  18. from twisted.internet.defer import Deferred
  19. from twisted.internet.interfaces import IAddress, IConnector
  20. from twisted.internet.protocol import ReconnectingClientFactory
  21. from twisted.python.failure import Failure
  22. from synapse.api.constants import EventTypes, ReceiptTypes
  23. from synapse.federation import send_queue
  24. from synapse.federation.sender import FederationSender
  25. from synapse.logging.context import PreserveLoggingContext, make_deferred_yieldable
  26. from synapse.metrics.background_process_metrics import run_as_background_process
  27. from synapse.replication.tcp.protocol import ClientReplicationStreamProtocol
  28. from synapse.replication.tcp.streams import (
  29. AccountDataStream,
  30. DeviceListsStream,
  31. GroupServerStream,
  32. PushersStream,
  33. PushRulesStream,
  34. ReceiptsStream,
  35. TagAccountDataStream,
  36. ToDeviceStream,
  37. TypingStream,
  38. )
  39. from synapse.replication.tcp.streams.events import (
  40. EventsStream,
  41. EventsStreamEventRow,
  42. EventsStreamRow,
  43. )
  44. from synapse.types import PersistedEventPosition, ReadReceipt, StreamKeyType, UserID
  45. from synapse.util.async_helpers import Linearizer, timeout_deferred
  46. from synapse.util.metrics import Measure
  47. if TYPE_CHECKING:
  48. from synapse.replication.tcp.handler import ReplicationCommandHandler
  49. from synapse.server import HomeServer
  50. logger = logging.getLogger(__name__)
  51. # How long we allow callers to wait for replication updates before timing out.
  52. _WAIT_FOR_REPLICATION_TIMEOUT_SECONDS = 30
  53. class DirectTcpReplicationClientFactory(ReconnectingClientFactory):
  54. """Factory for building connections to the master. Will reconnect if the
  55. connection is lost.
  56. Accepts a handler that is passed to `ClientReplicationStreamProtocol`.
  57. """
  58. initialDelay = 0.1
  59. maxDelay = 1 # Try at least once every N seconds
  60. def __init__(
  61. self,
  62. hs: "HomeServer",
  63. client_name: str,
  64. command_handler: "ReplicationCommandHandler",
  65. ):
  66. self.client_name = client_name
  67. self.command_handler = command_handler
  68. self.server_name = hs.config.server.server_name
  69. self.hs = hs
  70. self._clock = hs.get_clock() # As self.clock is defined in super class
  71. hs.get_reactor().addSystemEventTrigger("before", "shutdown", self.stopTrying)
  72. def startedConnecting(self, connector: IConnector) -> None:
  73. logger.info("Connecting to replication: %r", connector.getDestination())
  74. def buildProtocol(self, addr: IAddress) -> ClientReplicationStreamProtocol:
  75. logger.info("Connected to replication: %r", addr)
  76. return ClientReplicationStreamProtocol(
  77. self.hs,
  78. self.client_name,
  79. self.server_name,
  80. self._clock,
  81. self.command_handler,
  82. )
  83. def clientConnectionLost(self, connector: IConnector, reason: Failure) -> None:
  84. logger.error("Lost replication conn: %r", reason)
  85. ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
  86. def clientConnectionFailed(self, connector: IConnector, reason: Failure) -> None:
  87. logger.error("Failed to connect to replication: %r", reason)
  88. ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
  89. class ReplicationDataHandler:
  90. """Handles incoming stream updates from replication.
  91. This instance notifies the slave data store about updates. Can be subclassed
  92. to handle updates in additional ways.
  93. """
  94. def __init__(self, hs: "HomeServer"):
  95. self.store = hs.get_datastores().main
  96. self.notifier = hs.get_notifier()
  97. self._reactor = hs.get_reactor()
  98. self._clock = hs.get_clock()
  99. self._streams = hs.get_replication_streams()
  100. self._instance_name = hs.get_instance_name()
  101. self._typing_handler = hs.get_typing_handler()
  102. self._notify_pushers = hs.config.worker.start_pushers
  103. self._pusher_pool = hs.get_pusherpool()
  104. self._presence_handler = hs.get_presence_handler()
  105. self.send_handler: Optional[FederationSenderHandler] = None
  106. if hs.should_send_federation():
  107. self.send_handler = FederationSenderHandler(hs)
  108. # Map from stream to list of deferreds waiting for the stream to
  109. # arrive at a particular position. The lists are sorted by stream position.
  110. self._streams_to_waiters: Dict[str, List[Tuple[int, Deferred]]] = {}
  111. async def on_rdata(
  112. self, stream_name: str, instance_name: str, token: int, rows: list
  113. ) -> None:
  114. """Called to handle a batch of replication data with a given stream token.
  115. By default this just pokes the slave store. Can be overridden in subclasses to
  116. handle more.
  117. Args:
  118. stream_name: name of the replication stream for this batch of rows
  119. instance_name: the instance that wrote the rows.
  120. token: stream token for this batch of rows
  121. rows: a list of Stream.ROW_TYPE objects as returned by Stream.parse_row.
  122. """
  123. self.store.process_replication_rows(stream_name, instance_name, token, rows)
  124. if self.send_handler:
  125. await self.send_handler.process_replication_rows(stream_name, token, rows)
  126. if stream_name == TypingStream.NAME:
  127. self._typing_handler.process_replication_rows(token, rows)
  128. self.notifier.on_new_event(
  129. StreamKeyType.TYPING, token, rooms=[row.room_id for row in rows]
  130. )
  131. elif stream_name == PushRulesStream.NAME:
  132. self.notifier.on_new_event(
  133. StreamKeyType.PUSH_RULES, token, users=[row.user_id for row in rows]
  134. )
  135. elif stream_name in (AccountDataStream.NAME, TagAccountDataStream.NAME):
  136. self.notifier.on_new_event(
  137. StreamKeyType.ACCOUNT_DATA, token, users=[row.user_id for row in rows]
  138. )
  139. elif stream_name == ReceiptsStream.NAME:
  140. self.notifier.on_new_event(
  141. StreamKeyType.RECEIPT, token, rooms=[row.room_id for row in rows]
  142. )
  143. await self._pusher_pool.on_new_receipts(
  144. token, token, {row.room_id for row in rows}
  145. )
  146. elif stream_name == ToDeviceStream.NAME:
  147. entities = [row.entity for row in rows if row.entity.startswith("@")]
  148. if entities:
  149. self.notifier.on_new_event(
  150. StreamKeyType.TO_DEVICE, token, users=entities
  151. )
  152. elif stream_name == DeviceListsStream.NAME:
  153. all_room_ids: Set[str] = set()
  154. for row in rows:
  155. if row.entity.startswith("@"):
  156. room_ids = await self.store.get_rooms_for_user(row.entity)
  157. all_room_ids.update(room_ids)
  158. self.notifier.on_new_event(
  159. StreamKeyType.DEVICE_LIST, token, rooms=all_room_ids
  160. )
  161. elif stream_name == GroupServerStream.NAME:
  162. self.notifier.on_new_event(
  163. "groups_key", token, users=[row.user_id for row in rows]
  164. )
  165. elif stream_name == PushersStream.NAME:
  166. for row in rows:
  167. if row.deleted:
  168. self.stop_pusher(row.user_id, row.app_id, row.pushkey)
  169. else:
  170. await self.start_pusher(row.user_id, row.app_id, row.pushkey)
  171. elif stream_name == EventsStream.NAME:
  172. # We shouldn't get multiple rows per token for events stream, so
  173. # we don't need to optimise this for multiple rows.
  174. for row in rows:
  175. if row.type != EventsStreamEventRow.TypeId:
  176. continue
  177. assert isinstance(row, EventsStreamRow)
  178. assert isinstance(row.data, EventsStreamEventRow)
  179. if row.data.rejected:
  180. continue
  181. extra_users: Tuple[UserID, ...] = ()
  182. if row.data.type == EventTypes.Member and row.data.state_key:
  183. extra_users = (UserID.from_string(row.data.state_key),)
  184. max_token = self.store.get_room_max_token()
  185. event_pos = PersistedEventPosition(instance_name, token)
  186. await self.notifier.on_new_room_event_args(
  187. event_pos=event_pos,
  188. max_room_stream_token=max_token,
  189. extra_users=extra_users,
  190. room_id=row.data.room_id,
  191. event_id=row.data.event_id,
  192. event_type=row.data.type,
  193. state_key=row.data.state_key,
  194. membership=row.data.membership,
  195. )
  196. await self._presence_handler.process_replication_rows(
  197. stream_name, instance_name, token, rows
  198. )
  199. # Notify any waiting deferreds. The list is ordered by position so we
  200. # just iterate through the list until we reach a position that is
  201. # greater than the received row position.
  202. waiting_list = self._streams_to_waiters.get(stream_name, [])
  203. # Index of first item with a position after the current token, i.e we
  204. # have called all deferreds before this index. If not overwritten by
  205. # loop below means either a) no items in list so no-op or b) all items
  206. # in list were called and so the list should be cleared. Setting it to
  207. # `len(list)` works for both cases.
  208. index_of_first_deferred_not_called = len(waiting_list)
  209. for idx, (position, deferred) in enumerate(waiting_list):
  210. if position <= token:
  211. try:
  212. with PreserveLoggingContext():
  213. deferred.callback(None)
  214. except Exception:
  215. # The deferred has been cancelled or timed out.
  216. pass
  217. else:
  218. # The list is sorted by position so we don't need to continue
  219. # checking any further entries in the list.
  220. index_of_first_deferred_not_called = idx
  221. break
  222. # Drop all entries in the waiting list that were called in the above
  223. # loop. (This maintains the order so no need to resort)
  224. waiting_list[:] = waiting_list[index_of_first_deferred_not_called:]
  225. async def on_position(
  226. self, stream_name: str, instance_name: str, token: int
  227. ) -> None:
  228. await self.on_rdata(stream_name, instance_name, token, [])
  229. # We poke the generic "replication" notifier to wake anything up that
  230. # may be streaming.
  231. self.notifier.notify_replication()
  232. def on_remote_server_up(self, server: str) -> None:
  233. """Called when get a new REMOTE_SERVER_UP command."""
  234. # Let's wake up the transaction queue for the server in case we have
  235. # pending stuff to send to it.
  236. if self.send_handler:
  237. self.send_handler.wake_destination(server)
  238. async def wait_for_stream_position(
  239. self, instance_name: str, stream_name: str, position: int
  240. ) -> None:
  241. """Wait until this instance has received updates up to and including
  242. the given stream position.
  243. """
  244. if instance_name == self._instance_name:
  245. # We don't get told about updates written by this process, and
  246. # anyway in that case we don't need to wait.
  247. return
  248. current_position = self._streams[stream_name].current_token(self._instance_name)
  249. if position <= current_position:
  250. # We're already past the position
  251. return
  252. # Create a new deferred that times out after N seconds, as we don't want
  253. # to wedge here forever.
  254. deferred: "Deferred[None]" = Deferred()
  255. deferred = timeout_deferred(
  256. deferred, _WAIT_FOR_REPLICATION_TIMEOUT_SECONDS, self._reactor
  257. )
  258. waiting_list = self._streams_to_waiters.setdefault(stream_name, [])
  259. waiting_list.append((position, deferred))
  260. waiting_list.sort(key=lambda t: t[0])
  261. # We measure here to get in flight counts and average waiting time.
  262. with Measure(self._clock, "repl.wait_for_stream_position"):
  263. logger.info("Waiting for repl stream %r to reach %s", stream_name, position)
  264. await make_deferred_yieldable(deferred)
  265. logger.info(
  266. "Finished waiting for repl stream %r to reach %s", stream_name, position
  267. )
  268. def stop_pusher(self, user_id: str, app_id: str, pushkey: str) -> None:
  269. if not self._notify_pushers:
  270. return
  271. key = "%s:%s" % (app_id, pushkey)
  272. pushers_for_user = self._pusher_pool.pushers.get(user_id, {})
  273. pusher = pushers_for_user.pop(key, None)
  274. if pusher is None:
  275. return
  276. logger.info("Stopping pusher %r / %r", user_id, key)
  277. pusher.on_stop()
  278. async def start_pusher(self, user_id: str, app_id: str, pushkey: str) -> None:
  279. if not self._notify_pushers:
  280. return
  281. key = "%s:%s" % (app_id, pushkey)
  282. logger.info("Starting pusher %r / %r", user_id, key)
  283. await self._pusher_pool.start_pusher_by_id(app_id, pushkey, user_id)
  284. class FederationSenderHandler:
  285. """Processes the fedration replication stream
  286. This class is only instantiate on the worker responsible for sending outbound
  287. federation transactions. It receives rows from the replication stream and forwards
  288. the appropriate entries to the FederationSender class.
  289. """
  290. def __init__(self, hs: "HomeServer"):
  291. assert hs.should_send_federation()
  292. self.store = hs.get_datastores().main
  293. self._is_mine_id = hs.is_mine_id
  294. self._hs = hs
  295. # We need to make a temporary value to ensure that mypy picks up the
  296. # right type. We know we should have a federation sender instance since
  297. # `should_send_federation` is True.
  298. sender = hs.get_federation_sender()
  299. assert isinstance(sender, FederationSender)
  300. self.federation_sender = sender
  301. # Stores the latest position in the federation stream we've gotten up
  302. # to. This is always set before we use it.
  303. self.federation_position: Optional[int] = None
  304. self._fed_position_linearizer = Linearizer(name="_fed_position_linearizer")
  305. def wake_destination(self, server: str) -> None:
  306. self.federation_sender.wake_destination(server)
  307. async def process_replication_rows(
  308. self, stream_name: str, token: int, rows: list
  309. ) -> None:
  310. # The federation stream contains things that we want to send out, e.g.
  311. # presence, typing, etc.
  312. if stream_name == "federation":
  313. send_queue.process_rows_for_federation(self.federation_sender, rows)
  314. await self.update_token(token)
  315. # ... and when new receipts happen
  316. elif stream_name == ReceiptsStream.NAME:
  317. await self._on_new_receipts(rows)
  318. # ... as well as device updates and messages
  319. elif stream_name == DeviceListsStream.NAME:
  320. # The entities are either user IDs (starting with '@') whose devices
  321. # have changed, or remote servers that we need to tell about
  322. # changes.
  323. hosts = {row.entity for row in rows if not row.entity.startswith("@")}
  324. for host in hosts:
  325. self.federation_sender.send_device_messages(host, immediate=False)
  326. elif stream_name == ToDeviceStream.NAME:
  327. # The to_device stream includes stuff to be pushed to both local
  328. # clients and remote servers, so we ignore entities that start with
  329. # '@' (since they'll be local users rather than destinations).
  330. hosts = {row.entity for row in rows if not row.entity.startswith("@")}
  331. for host in hosts:
  332. self.federation_sender.send_device_messages(host)
  333. async def _on_new_receipts(
  334. self, rows: Iterable[ReceiptsStream.ReceiptsStreamRow]
  335. ) -> None:
  336. """
  337. Args:
  338. rows: new receipts to be processed
  339. """
  340. for receipt in rows:
  341. # we only want to send on receipts for our own users
  342. if not self._is_mine_id(receipt.user_id):
  343. continue
  344. # Private read receipts never get sent over federation.
  345. if receipt.receipt_type == ReceiptTypes.READ_PRIVATE:
  346. continue
  347. receipt_info = ReadReceipt(
  348. receipt.room_id,
  349. receipt.receipt_type,
  350. receipt.user_id,
  351. [receipt.event_id],
  352. receipt.data,
  353. )
  354. await self.federation_sender.send_read_receipt(receipt_info)
  355. async def update_token(self, token: int) -> None:
  356. """Update the record of where we have processed to in the federation stream.
  357. Called after we have processed a an update received over replication. Sends
  358. a FEDERATION_ACK back to the master, and stores the token that we have processed
  359. in `federation_stream_position` so that we can restart where we left off.
  360. """
  361. self.federation_position = token
  362. # We save and send the ACK to master asynchronously, so we don't block
  363. # processing on persistence. We don't need to do this operation for
  364. # every single RDATA we receive, we just need to do it periodically.
  365. if self._fed_position_linearizer.is_queued(None):
  366. # There is already a task queued up to save and send the token, so
  367. # no need to queue up another task.
  368. return
  369. run_as_background_process("_save_and_send_ack", self._save_and_send_ack)
  370. async def _save_and_send_ack(self) -> None:
  371. """Save the current federation position in the database and send an ACK
  372. to master with where we're up to.
  373. """
  374. # We should only be calling this once we've got a token.
  375. assert self.federation_position is not None
  376. try:
  377. # We linearize here to ensure we don't have races updating the token
  378. #
  379. # XXX this appears to be redundant, since the ReplicationCommandHandler
  380. # has a linearizer which ensures that we only process one line of
  381. # replication data at a time. Should we remove it, or is it doing useful
  382. # service for robustness? Or could we replace it with an assertion that
  383. # we're not being re-entered?
  384. async with self._fed_position_linearizer.queue(None):
  385. # We persist and ack the same position, so we take a copy of it
  386. # here as otherwise it can get modified from underneath us.
  387. current_position = self.federation_position
  388. await self.store.update_federation_out_pos(
  389. "federation", current_position
  390. )
  391. # We ACK this token over replication so that the master can drop
  392. # its in memory queues
  393. self._hs.get_replication_command_handler().send_federation_ack(
  394. current_position
  395. )
  396. except Exception:
  397. logger.exception("Error updating federation stream position")