1
0

_base.py 20 KB

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