_base.py 20 KB

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