_base.py 22 KB

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