_base.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 New Vector 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. import logging
  16. from typing import Any, List, Optional, Tuple
  17. import attr
  18. from twisted.internet.interfaces import IConsumer, IPullProducer, IReactorTime
  19. from twisted.internet.task import LoopingCall
  20. from twisted.web.http import HTTPChannel
  21. from synapse.app.generic_worker import (
  22. GenericWorkerReplicationHandler,
  23. GenericWorkerServer,
  24. )
  25. from synapse.http.site import SynapseRequest
  26. from synapse.replication.http import streams
  27. from synapse.replication.tcp.handler import ReplicationCommandHandler
  28. from synapse.replication.tcp.protocol import ClientReplicationStreamProtocol
  29. from synapse.replication.tcp.resource import ReplicationStreamProtocolFactory
  30. from synapse.server import HomeServer
  31. from synapse.util import Clock
  32. from tests import unittest
  33. from tests.server import FakeTransport
  34. logger = logging.getLogger(__name__)
  35. class BaseStreamTestCase(unittest.HomeserverTestCase):
  36. """Base class for tests of the replication streams"""
  37. servlets = [
  38. streams.register_servlets,
  39. ]
  40. def prepare(self, reactor, clock, hs):
  41. # build a replication server
  42. server_factory = ReplicationStreamProtocolFactory(hs)
  43. self.streamer = hs.get_replication_streamer()
  44. self.server = server_factory.buildProtocol(None)
  45. # Make a new HomeServer object for the worker
  46. self.reactor.lookups["testserv"] = "1.2.3.4"
  47. self.worker_hs = self.setup_test_homeserver(
  48. http_client=None,
  49. homeserverToUse=GenericWorkerServer,
  50. config=self._get_worker_hs_config(),
  51. reactor=self.reactor,
  52. )
  53. # Since we use sqlite in memory databases we need to make sure the
  54. # databases objects are the same.
  55. self.worker_hs.get_datastore().db = hs.get_datastore().db
  56. self.test_handler = self._build_replication_data_handler()
  57. self.worker_hs.replication_data_handler = self.test_handler
  58. repl_handler = ReplicationCommandHandler(self.worker_hs)
  59. self.client = ClientReplicationStreamProtocol(
  60. self.worker_hs, "client", "test", clock, repl_handler,
  61. )
  62. self._client_transport = None
  63. self._server_transport = None
  64. def _get_worker_hs_config(self) -> dict:
  65. config = self.default_config()
  66. config["worker_app"] = "synapse.app.generic_worker"
  67. config["worker_replication_host"] = "testserv"
  68. config["worker_replication_http_port"] = "8765"
  69. return config
  70. def _build_replication_data_handler(self):
  71. return TestReplicationDataHandler(self.worker_hs)
  72. def reconnect(self):
  73. if self._client_transport:
  74. self.client.close()
  75. if self._server_transport:
  76. self.server.close()
  77. self._client_transport = FakeTransport(self.server, self.reactor)
  78. self.client.makeConnection(self._client_transport)
  79. self._server_transport = FakeTransport(self.client, self.reactor)
  80. self.server.makeConnection(self._server_transport)
  81. def disconnect(self):
  82. if self._client_transport:
  83. self._client_transport = None
  84. self.client.close()
  85. if self._server_transport:
  86. self._server_transport = None
  87. self.server.close()
  88. def replicate(self):
  89. """Tell the master side of replication that something has happened, and then
  90. wait for the replication to occur.
  91. """
  92. self.streamer.on_notifier_poke()
  93. self.pump(0.1)
  94. def handle_http_replication_attempt(self) -> SynapseRequest:
  95. """Asserts that a connection attempt was made to the master HS on the
  96. HTTP replication port, then proxies it to the master HS object to be
  97. handled.
  98. Returns:
  99. The request object received by master HS.
  100. """
  101. # We should have an outbound connection attempt.
  102. clients = self.reactor.tcpClients
  103. self.assertEqual(len(clients), 1)
  104. (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0)
  105. self.assertEqual(host, "1.2.3.4")
  106. self.assertEqual(port, 8765)
  107. # Set up client side protocol
  108. client_protocol = client_factory.buildProtocol(None)
  109. request_factory = OneShotRequestFactory()
  110. # Set up the server side protocol
  111. channel = _PushHTTPChannel(self.reactor)
  112. channel.requestFactory = request_factory
  113. channel.site = self.site
  114. # Connect client to server and vice versa.
  115. client_to_server_transport = FakeTransport(
  116. channel, self.reactor, client_protocol
  117. )
  118. client_protocol.makeConnection(client_to_server_transport)
  119. server_to_client_transport = FakeTransport(
  120. client_protocol, self.reactor, channel
  121. )
  122. channel.makeConnection(server_to_client_transport)
  123. # The request will now be processed by `self.site` and the response
  124. # streamed back.
  125. self.reactor.advance(0)
  126. # We tear down the connection so it doesn't get reused without our
  127. # knowledge.
  128. server_to_client_transport.loseConnection()
  129. client_to_server_transport.loseConnection()
  130. return request_factory.request
  131. def assert_request_is_get_repl_stream_updates(
  132. self, request: SynapseRequest, stream_name: str
  133. ):
  134. """Asserts that the given request is a HTTP replication request for
  135. fetching updates for given stream.
  136. """
  137. self.assertRegex(
  138. request.path,
  139. br"^/_synapse/replication/get_repl_stream_updates/%s/[^/]+$"
  140. % (stream_name.encode("ascii"),),
  141. )
  142. self.assertEqual(request.method, b"GET")
  143. class TestReplicationDataHandler(GenericWorkerReplicationHandler):
  144. """Drop-in for ReplicationDataHandler which just collects RDATA rows"""
  145. def __init__(self, hs: HomeServer):
  146. super().__init__(hs)
  147. # list of received (stream_name, token, row) tuples
  148. self.received_rdata_rows = [] # type: List[Tuple[str, int, Any]]
  149. async def on_rdata(self, stream_name, instance_name, token, rows):
  150. await super().on_rdata(stream_name, instance_name, token, rows)
  151. for r in rows:
  152. self.received_rdata_rows.append((stream_name, token, r))
  153. @attr.s()
  154. class OneShotRequestFactory:
  155. """A simple request factory that generates a single `SynapseRequest` and
  156. stores it for future use. Can only be used once.
  157. """
  158. request = attr.ib(default=None)
  159. def __call__(self, *args, **kwargs):
  160. assert self.request is None
  161. self.request = SynapseRequest(*args, **kwargs)
  162. return self.request
  163. class _PushHTTPChannel(HTTPChannel):
  164. """A HTTPChannel that wraps pull producers to push producers.
  165. This is a hack to get around the fact that HTTPChannel transparently wraps a
  166. pull producer (which is what Synapse uses to reply to requests) with
  167. `_PullToPush` to convert it to a push producer. Unfortunately `_PullToPush`
  168. uses the standard reactor rather than letting us use our test reactor, which
  169. makes it very hard to test.
  170. """
  171. def __init__(self, reactor: IReactorTime):
  172. super().__init__()
  173. self.reactor = reactor
  174. self._pull_to_push_producer = None # type: Optional[_PullToPushProducer]
  175. def registerProducer(self, producer, streaming):
  176. # Convert pull producers to push producer.
  177. if not streaming:
  178. self._pull_to_push_producer = _PullToPushProducer(
  179. self.reactor, producer, self
  180. )
  181. producer = self._pull_to_push_producer
  182. super().registerProducer(producer, True)
  183. def unregisterProducer(self):
  184. if self._pull_to_push_producer:
  185. # We need to manually stop the _PullToPushProducer.
  186. self._pull_to_push_producer.stop()
  187. class _PullToPushProducer:
  188. """A push producer that wraps a pull producer.
  189. """
  190. def __init__(
  191. self, reactor: IReactorTime, producer: IPullProducer, consumer: IConsumer
  192. ):
  193. self._clock = Clock(reactor)
  194. self._producer = producer
  195. self._consumer = consumer
  196. # While running we use a looping call with a zero delay to call
  197. # resumeProducing on given producer.
  198. self._looping_call = None # type: Optional[LoopingCall]
  199. # We start writing next reactor tick.
  200. self._start_loop()
  201. def _start_loop(self):
  202. """Start the looping call to
  203. """
  204. if not self._looping_call:
  205. # Start a looping call which runs every tick.
  206. self._looping_call = self._clock.looping_call(self._run_once, 0)
  207. def stop(self):
  208. """Stops calling resumeProducing.
  209. """
  210. if self._looping_call:
  211. self._looping_call.stop()
  212. self._looping_call = None
  213. def pauseProducing(self):
  214. """Implements IPushProducer
  215. """
  216. self.stop()
  217. def resumeProducing(self):
  218. """Implements IPushProducer
  219. """
  220. self._start_loop()
  221. def stopProducing(self):
  222. """Implements IPushProducer
  223. """
  224. self.stop()
  225. self._producer.stopProducing()
  226. def _run_once(self):
  227. """Calls resumeProducing on producer once.
  228. """
  229. try:
  230. self._producer.resumeProducing()
  231. except Exception:
  232. logger.exception("Failed to call resumeProducing")
  233. try:
  234. self._consumer.unregisterProducer()
  235. except Exception:
  236. pass
  237. self.stopProducing()