_base.py 22 KB

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