_base.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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 collections import defaultdict
  16. from typing import Any, Dict, List, Optional, Set, Tuple
  17. from twisted.internet.address import IPv4Address
  18. from twisted.internet.protocol import Protocol, connectionDone
  19. from twisted.python.failure import Failure
  20. from twisted.test.proto_helpers import MemoryReactor
  21. from twisted.web.resource import Resource
  22. from synapse.app.generic_worker import GenericWorkerServer
  23. from synapse.http.site import SynapseRequest, SynapseSite
  24. from synapse.replication.http import ReplicationRestResource
  25. from synapse.replication.tcp.client import ReplicationDataHandler
  26. from synapse.replication.tcp.handler import ReplicationCommandHandler
  27. from synapse.replication.tcp.protocol import (
  28. ClientReplicationStreamProtocol,
  29. ServerReplicationStreamProtocol,
  30. )
  31. from synapse.replication.tcp.resource import ReplicationStreamProtocolFactory
  32. from synapse.server import HomeServer
  33. from synapse.util import Clock
  34. from tests import unittest
  35. from tests.server import FakeTransport
  36. from tests.utils import USE_POSTGRES_FOR_TESTS
  37. try:
  38. import hiredis
  39. except ImportError:
  40. hiredis = None # type: ignore
  41. logger = logging.getLogger(__name__)
  42. class BaseStreamTestCase(unittest.HomeserverTestCase):
  43. """Base class for tests of the replication streams"""
  44. # hiredis is an optional dependency so we don't want to require it for running
  45. # the tests.
  46. if not hiredis:
  47. skip = "Requires hiredis"
  48. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  49. # build a replication server
  50. server_factory = ReplicationStreamProtocolFactory(hs)
  51. self.streamer = hs.get_replication_streamer()
  52. self.server: ServerReplicationStreamProtocol = server_factory.buildProtocol(
  53. IPv4Address("TCP", "127.0.0.1", 0)
  54. )
  55. # Make a new HomeServer object for the worker
  56. self.reactor.lookups["testserv"] = "1.2.3.4"
  57. self.worker_hs = self.setup_test_homeserver(
  58. federation_http_client=None,
  59. homeserver_to_use=GenericWorkerServer,
  60. config=self._get_worker_hs_config(),
  61. reactor=self.reactor,
  62. )
  63. # Since we use sqlite in memory databases we need to make sure the
  64. # databases objects are the same.
  65. self.worker_hs.get_datastores().main.db_pool = hs.get_datastores().main.db_pool
  66. # Normally we'd pass in the handler to `setup_test_homeserver`, which would
  67. # eventually hit "Install @cache_in_self attributes" in tests/utils.py.
  68. # Unfortunately our handler wants a reference to the homeserver. That leaves
  69. # us with a chicken-and-egg problem.
  70. # We can workaround this: create the homeserver first, create the handler
  71. # and bodge it in after the fact. The bodging requires us to know the
  72. # dirty details of how `cache_in_self` works. We politely ask mypy to
  73. # ignore our dirty dealings.
  74. self.test_handler = self._build_replication_data_handler()
  75. self.worker_hs._replication_data_handler = self.test_handler # type: ignore[attr-defined]
  76. repl_handler = ReplicationCommandHandler(self.worker_hs)
  77. self.client = ClientReplicationStreamProtocol(
  78. self.worker_hs,
  79. "client",
  80. "test",
  81. clock,
  82. repl_handler,
  83. )
  84. self._client_transport: Optional[FakeTransport] = None
  85. self._server_transport: Optional[FakeTransport] = None
  86. def create_resource_dict(self) -> Dict[str, Resource]:
  87. d = super().create_resource_dict()
  88. d["/_synapse/replication"] = ReplicationRestResource(self.hs)
  89. return d
  90. def _get_worker_hs_config(self) -> dict:
  91. config = self.default_config()
  92. config["worker_app"] = "synapse.app.generic_worker"
  93. config["worker_replication_host"] = "testserv"
  94. config["worker_replication_http_port"] = "8765"
  95. return config
  96. def _build_replication_data_handler(self) -> "TestReplicationDataHandler":
  97. return TestReplicationDataHandler(self.worker_hs)
  98. def reconnect(self) -> None:
  99. if self._client_transport:
  100. self.client.close()
  101. if self._server_transport:
  102. self.server.close()
  103. self._client_transport = FakeTransport(self.server, self.reactor)
  104. self.client.makeConnection(self._client_transport)
  105. self._server_transport = FakeTransport(self.client, self.reactor)
  106. self.server.makeConnection(self._server_transport)
  107. def disconnect(self) -> None:
  108. if self._client_transport:
  109. self._client_transport = None
  110. self.client.close()
  111. if self._server_transport:
  112. self._server_transport = None
  113. self.server.close()
  114. def replicate(self) -> None:
  115. """Tell the master side of replication that something has happened, and then
  116. wait for the replication to occur.
  117. """
  118. self.streamer.on_notifier_poke()
  119. self.pump(0.1)
  120. def handle_http_replication_attempt(self) -> SynapseRequest:
  121. """Asserts that a connection attempt was made to the master HS on the
  122. HTTP replication port, then proxies it to the master HS object to be
  123. handled.
  124. Returns:
  125. The request object received by master HS.
  126. """
  127. # We should have an outbound connection attempt.
  128. clients = self.reactor.tcpClients
  129. self.assertEqual(len(clients), 1)
  130. (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0)
  131. self.assertEqual(host, "1.2.3.4")
  132. self.assertEqual(port, 8765)
  133. # Set up client side protocol
  134. client_address = IPv4Address("TCP", "127.0.0.1", 1234)
  135. client_protocol = client_factory.buildProtocol(("127.0.0.1", 1234))
  136. # Set up the server side protocol
  137. server_address = IPv4Address("TCP", host, port)
  138. channel = self.site.buildProtocol((host, port))
  139. # hook into the channel's request factory so that we can keep a record
  140. # of the requests
  141. requests: List[SynapseRequest] = []
  142. real_request_factory = channel.requestFactory
  143. def request_factory(*args: Any, **kwargs: Any) -> SynapseRequest:
  144. request = real_request_factory(*args, **kwargs)
  145. requests.append(request)
  146. return request
  147. channel.requestFactory = request_factory
  148. # Connect client to server and vice versa.
  149. client_to_server_transport = FakeTransport(
  150. channel, self.reactor, client_protocol, server_address, client_address
  151. )
  152. client_protocol.makeConnection(client_to_server_transport)
  153. server_to_client_transport = FakeTransport(
  154. client_protocol, self.reactor, channel, client_address, server_address
  155. )
  156. channel.makeConnection(server_to_client_transport)
  157. # The request will now be processed by `self.site` and the response
  158. # streamed back.
  159. self.reactor.advance(0)
  160. # We tear down the connection so it doesn't get reused without our
  161. # knowledge.
  162. server_to_client_transport.loseConnection()
  163. client_to_server_transport.loseConnection()
  164. # there should have been exactly one request
  165. self.assertEqual(len(requests), 1)
  166. return requests[0]
  167. def assert_request_is_get_repl_stream_updates(
  168. self, request: SynapseRequest, stream_name: str
  169. ) -> None:
  170. """Asserts that the given request is a HTTP replication request for
  171. fetching updates for given stream.
  172. """
  173. path: bytes = request.path # type: ignore
  174. self.assertRegex(
  175. path,
  176. rb"^/_synapse/replication/get_repl_stream_updates/%s/[^/]+$"
  177. % (stream_name.encode("ascii"),),
  178. )
  179. self.assertEqual(request.method, b"GET")
  180. class BaseMultiWorkerStreamTestCase(unittest.HomeserverTestCase):
  181. """Base class for tests running multiple workers.
  182. Enables Redis, providing a fake Redis server.
  183. Automatically handle HTTP replication requests from workers to master,
  184. unlike `BaseStreamTestCase`.
  185. """
  186. if not hiredis:
  187. skip = "Requires hiredis"
  188. if not USE_POSTGRES_FOR_TESTS:
  189. # Redis replication only takes place on Postgres
  190. skip = "Requires Postgres"
  191. def default_config(self) -> Dict[str, Any]:
  192. """
  193. Overrides the default config to enable Redis.
  194. Even if the test only uses make_worker_hs, the main process needs Redis
  195. enabled otherwise it won't create a Fake Redis server to listen on the
  196. Redis port and accept fake TCP connections.
  197. """
  198. base = super().default_config()
  199. base["redis"] = {"enabled": True}
  200. return base
  201. def setUp(self) -> None:
  202. super().setUp()
  203. # build a replication server
  204. self.streamer = self.hs.get_replication_streamer()
  205. # Fake in memory Redis server that servers can connect to.
  206. self._redis_server = FakeRedisPubSubServer()
  207. # We may have an attempt to connect to redis for the external cache already.
  208. self.connect_any_redis_attempts()
  209. store = self.hs.get_datastores().main
  210. self.database_pool = store.db_pool
  211. self.reactor.lookups["testserv"] = "1.2.3.4"
  212. self.reactor.lookups["localhost"] = "127.0.0.1"
  213. # A map from a HS instance to the associated HTTP Site to use for
  214. # handling inbound HTTP requests to that instance.
  215. self._hs_to_site = {self.hs: self.site}
  216. # Handle attempts to connect to fake redis server.
  217. self.reactor.add_tcp_client_callback(
  218. "localhost",
  219. 6379,
  220. self.connect_any_redis_attempts,
  221. )
  222. self.hs.get_replication_command_handler().start_replication(self.hs)
  223. # When we see a connection attempt to the master replication listener we
  224. # automatically set up the connection. This is so that tests don't
  225. # manually have to go and explicitly set it up each time (plus sometimes
  226. # it is impossible to write the handling explicitly in the tests).
  227. #
  228. # Register the master replication listener:
  229. self.reactor.add_tcp_client_callback(
  230. "1.2.3.4",
  231. 8765,
  232. lambda: self._handle_http_replication_attempt(self.hs, 8765),
  233. )
  234. def create_test_resource(self) -> ReplicationRestResource:
  235. """Overrides `HomeserverTestCase.create_test_resource`."""
  236. # We override this so that it automatically registers all the HTTP
  237. # replication servlets, without having to explicitly do that in all
  238. # subclassses.
  239. resource = ReplicationRestResource(self.hs)
  240. for servlet in self.servlets:
  241. servlet(self.hs, resource)
  242. return resource
  243. def make_worker_hs(
  244. self, worker_app: str, extra_config: Optional[dict] = None, **kwargs: Any
  245. ) -> HomeServer:
  246. """Make a new worker HS instance, correctly connecting replcation
  247. stream to the master HS.
  248. Args:
  249. worker_app: Type of worker, e.g. `synapse.app.generic_worker`.
  250. extra_config: Any extra config to use for this instances.
  251. **kwargs: Options that get passed to `self.setup_test_homeserver`,
  252. useful to e.g. pass some mocks for things like `federation_http_client`
  253. Returns:
  254. The new worker HomeServer instance.
  255. """
  256. config = self._get_worker_hs_config()
  257. config["worker_app"] = worker_app
  258. config.update(extra_config or {})
  259. worker_hs = self.setup_test_homeserver(
  260. homeserver_to_use=GenericWorkerServer,
  261. config=config,
  262. reactor=self.reactor,
  263. **kwargs,
  264. )
  265. # If the instance is in the `instance_map` config then workers may try
  266. # and send HTTP requests to it, so we register it with
  267. # `_handle_http_replication_attempt` like we do with the master HS.
  268. instance_name = worker_hs.get_instance_name()
  269. instance_loc = worker_hs.config.worker.instance_map.get(instance_name)
  270. if instance_loc:
  271. # Ensure the host is one that has a fake DNS entry.
  272. if instance_loc.host not in self.reactor.lookups:
  273. raise Exception(
  274. "Host does not have an IP for instance_map[%r].host = %r"
  275. % (
  276. instance_name,
  277. instance_loc.host,
  278. )
  279. )
  280. # Copy the port into a new, non-Optional variable so mypy knows we're
  281. # not going to reset `instance_loc` to `None` under its feet. See
  282. # https://mypy.readthedocs.io/en/latest/common_issues.html#narrowing-and-inner-functions
  283. port = instance_loc.port
  284. self.reactor.add_tcp_client_callback(
  285. self.reactor.lookups[instance_loc.host],
  286. instance_loc.port,
  287. lambda: self._handle_http_replication_attempt(worker_hs, port),
  288. )
  289. store = worker_hs.get_datastores().main
  290. store.db_pool._db_pool = self.database_pool._db_pool
  291. # Set up a resource for the worker
  292. resource = ReplicationRestResource(worker_hs)
  293. for servlet in self.servlets:
  294. servlet(worker_hs, resource)
  295. self._hs_to_site[worker_hs] = SynapseSite(
  296. logger_name="synapse.access.http.fake",
  297. site_tag="{}-{}".format(
  298. worker_hs.config.server.server_name, worker_hs.get_instance_name()
  299. ),
  300. config=worker_hs.config.server.listeners[0],
  301. resource=resource,
  302. server_version_string="1",
  303. max_request_body_size=8192,
  304. reactor=self.reactor,
  305. )
  306. worker_hs.get_replication_command_handler().start_replication(worker_hs)
  307. return worker_hs
  308. def _get_worker_hs_config(self) -> dict:
  309. config = self.default_config()
  310. config["worker_replication_host"] = "testserv"
  311. config["worker_replication_http_port"] = "8765"
  312. return config
  313. def replicate(self) -> None:
  314. """Tell the master side of replication that something has happened, and then
  315. wait for the replication to occur.
  316. """
  317. self.streamer.on_notifier_poke()
  318. self.pump()
  319. def _handle_http_replication_attempt(self, hs: HomeServer, repl_port: int) -> None:
  320. """Handles a connection attempt to the given HS replication HTTP
  321. listener on the given port.
  322. """
  323. # We should have at least one outbound connection attempt, where the
  324. # last is one to the HTTP repication IP/port.
  325. clients = self.reactor.tcpClients
  326. self.assertGreaterEqual(len(clients), 1)
  327. (host, port, client_factory, _timeout, _bindAddress) = clients.pop()
  328. self.assertEqual(host, "1.2.3.4")
  329. self.assertEqual(port, repl_port)
  330. # Set up client side protocol
  331. client_address = IPv4Address("TCP", "127.0.0.1", 1234)
  332. client_protocol = client_factory.buildProtocol(("127.0.0.1", 1234))
  333. # Set up the server side protocol
  334. server_address = IPv4Address("TCP", host, port)
  335. channel = self._hs_to_site[hs].buildProtocol((host, port))
  336. # Connect client to server and vice versa.
  337. client_to_server_transport = FakeTransport(
  338. channel, self.reactor, client_protocol, server_address, client_address
  339. )
  340. client_protocol.makeConnection(client_to_server_transport)
  341. server_to_client_transport = FakeTransport(
  342. client_protocol, self.reactor, channel, client_address, server_address
  343. )
  344. channel.makeConnection(server_to_client_transport)
  345. # Note: at this point we've wired everything up, but we need to return
  346. # before the data starts flowing over the connections as this is called
  347. # inside `connecTCP` before the connection has been passed back to the
  348. # code that requested the TCP connection.
  349. def connect_any_redis_attempts(self) -> None:
  350. """If redis is enabled we need to deal with workers connecting to a
  351. redis server. We don't want to use a real Redis server so we use a
  352. fake one.
  353. """
  354. clients = self.reactor.tcpClients
  355. while clients:
  356. (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0)
  357. self.assertEqual(host, "localhost")
  358. self.assertEqual(port, 6379)
  359. client_address = IPv4Address("TCP", "127.0.0.1", 6379)
  360. client_protocol = client_factory.buildProtocol(client_address)
  361. server_address = IPv4Address("TCP", host, port)
  362. server_protocol = self._redis_server.buildProtocol(server_address)
  363. client_to_server_transport = FakeTransport(
  364. server_protocol, self.reactor, client_protocol
  365. )
  366. client_protocol.makeConnection(client_to_server_transport)
  367. server_to_client_transport = FakeTransport(
  368. client_protocol, self.reactor, server_protocol
  369. )
  370. server_protocol.makeConnection(server_to_client_transport)
  371. class TestReplicationDataHandler(ReplicationDataHandler):
  372. """Drop-in for ReplicationDataHandler which just collects RDATA rows"""
  373. def __init__(self, hs: HomeServer):
  374. super().__init__(hs)
  375. # list of received (stream_name, token, row) tuples
  376. self.received_rdata_rows: List[Tuple[str, int, Any]] = []
  377. async def on_rdata(
  378. self, stream_name: str, instance_name: str, token: int, rows: list
  379. ) -> None:
  380. await super().on_rdata(stream_name, instance_name, token, rows)
  381. for r in rows:
  382. self.received_rdata_rows.append((stream_name, token, r))
  383. class FakeRedisPubSubServer:
  384. """A fake Redis server for pub/sub."""
  385. def __init__(self) -> None:
  386. self._subscribers_by_channel: Dict[
  387. bytes, Set["FakeRedisPubSubProtocol"]
  388. ] = defaultdict(set)
  389. def add_subscriber(self, conn: "FakeRedisPubSubProtocol", channel: bytes) -> None:
  390. """A connection has called SUBSCRIBE"""
  391. self._subscribers_by_channel[channel].add(conn)
  392. def remove_subscriber(self, conn: "FakeRedisPubSubProtocol") -> None:
  393. """A connection has lost connection"""
  394. for subscribers in self._subscribers_by_channel.values():
  395. subscribers.discard(conn)
  396. def publish(
  397. self, conn: "FakeRedisPubSubProtocol", channel: bytes, msg: object
  398. ) -> int:
  399. """A connection want to publish a message to subscribers."""
  400. for sub in self._subscribers_by_channel[channel]:
  401. sub.send(["message", channel, msg])
  402. return len(self._subscribers_by_channel)
  403. def buildProtocol(self, addr: IPv4Address) -> "FakeRedisPubSubProtocol":
  404. return FakeRedisPubSubProtocol(self)
  405. class FakeRedisPubSubProtocol(Protocol):
  406. """A connection from a client talking to the fake Redis server."""
  407. transport: Optional[FakeTransport] = None
  408. def __init__(self, server: FakeRedisPubSubServer):
  409. self._server = server
  410. self._reader = hiredis.Reader()
  411. def dataReceived(self, data: bytes) -> None:
  412. self._reader.feed(data)
  413. # We might get multiple messages in one packet.
  414. while True:
  415. msg = self._reader.gets()
  416. if msg is False:
  417. # No more messages.
  418. return
  419. if not isinstance(msg, list):
  420. # Inbound commands should always be a list
  421. raise Exception("Expected redis list")
  422. self.handle_command(msg[0], *msg[1:])
  423. def handle_command(self, command: bytes, *args: bytes) -> None:
  424. """Received a Redis command from the client."""
  425. # We currently only support pub/sub.
  426. if command == b"PUBLISH":
  427. channel, message = args
  428. num_subscribers = self._server.publish(self, channel, message)
  429. self.send(num_subscribers)
  430. elif command == b"SUBSCRIBE":
  431. for idx, channel in enumerate(args):
  432. num_channels = idx + 1
  433. self._server.add_subscriber(self, channel)
  434. self.send(["subscribe", channel, num_channels])
  435. # Since we use SET/GET to cache things we can safely no-op them.
  436. elif command == b"SET":
  437. self.send("OK")
  438. elif command == b"GET":
  439. self.send(None)
  440. # Connection keep-alives.
  441. elif command == b"PING":
  442. self.send("PONG")
  443. else:
  444. raise Exception(f"Unknown command: {command!r}")
  445. def send(self, msg: object) -> None:
  446. """Send a message back to the client."""
  447. assert self.transport is not None
  448. raw = self.encode(msg).encode("utf-8")
  449. self.transport.write(raw)
  450. self.transport.flush()
  451. def encode(self, obj: object) -> str:
  452. """Encode an object to its Redis format.
  453. Supports: strings/bytes, integers and list/tuples.
  454. """
  455. if isinstance(obj, bytes):
  456. # We assume bytes are just unicode strings.
  457. obj = obj.decode("utf-8")
  458. if obj is None:
  459. return "$-1\r\n"
  460. if isinstance(obj, str):
  461. return f"${len(obj)}\r\n{obj}\r\n"
  462. if isinstance(obj, int):
  463. return f":{obj}\r\n"
  464. if isinstance(obj, (list, tuple)):
  465. items = "".join(self.encode(a) for a in obj)
  466. return f"*{len(obj)}\r\n{items}"
  467. raise Exception("Unrecognized type for encoding redis: %r: %r", type(obj), obj)
  468. def connectionLost(self, reason: Failure = connectionDone) -> None:
  469. self._server.remove_subscriber(self)