_base.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import Any, Callable, Dict, List, Optional, Tuple
  17. import attr
  18. from twisted.internet.interfaces import IConsumer, IPullProducer, IReactorTime
  19. from twisted.internet.protocol import Protocol
  20. from twisted.internet.task import LoopingCall
  21. from twisted.web.http import HTTPChannel
  22. from twisted.web.resource import Resource
  23. from synapse.app.generic_worker import (
  24. GenericWorkerReplicationHandler,
  25. GenericWorkerServer,
  26. )
  27. from synapse.http.server import JsonResource
  28. from synapse.http.site import SynapseRequest, SynapseSite
  29. from synapse.replication.http import ReplicationRestResource
  30. from synapse.replication.tcp.handler import ReplicationCommandHandler
  31. from synapse.replication.tcp.protocol import ClientReplicationStreamProtocol
  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. try:
  38. import hiredis
  39. except ImportError:
  40. hiredis = None
  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, clock, hs):
  49. # build a replication server
  50. server_factory = ReplicationStreamProtocolFactory(hs)
  51. self.streamer = hs.get_replication_streamer()
  52. self.server = server_factory.buildProtocol(None)
  53. # Make a new HomeServer object for the worker
  54. self.reactor.lookups["testserv"] = "1.2.3.4"
  55. self.worker_hs = self.setup_test_homeserver(
  56. federation_http_client=None,
  57. homeserver_to_use=GenericWorkerServer,
  58. config=self._get_worker_hs_config(),
  59. reactor=self.reactor,
  60. )
  61. # Since we use sqlite in memory databases we need to make sure the
  62. # databases objects are the same.
  63. self.worker_hs.get_datastore().db_pool = hs.get_datastore().db_pool
  64. self.test_handler = self._build_replication_data_handler()
  65. self.worker_hs._replication_data_handler = self.test_handler
  66. repl_handler = ReplicationCommandHandler(self.worker_hs)
  67. self.client = ClientReplicationStreamProtocol(
  68. self.worker_hs,
  69. "client",
  70. "test",
  71. clock,
  72. repl_handler,
  73. )
  74. self._client_transport = None
  75. self._server_transport = None
  76. def create_resource_dict(self) -> Dict[str, Resource]:
  77. d = super().create_resource_dict()
  78. d["/_synapse/replication"] = ReplicationRestResource(self.hs)
  79. return d
  80. def _get_worker_hs_config(self) -> dict:
  81. config = self.default_config()
  82. config["worker_app"] = "synapse.app.generic_worker"
  83. config["worker_replication_host"] = "testserv"
  84. config["worker_replication_http_port"] = "8765"
  85. return config
  86. def _build_replication_data_handler(self):
  87. return TestReplicationDataHandler(self.worker_hs)
  88. def reconnect(self):
  89. if self._client_transport:
  90. self.client.close()
  91. if self._server_transport:
  92. self.server.close()
  93. self._client_transport = FakeTransport(self.server, self.reactor)
  94. self.client.makeConnection(self._client_transport)
  95. self._server_transport = FakeTransport(self.client, self.reactor)
  96. self.server.makeConnection(self._server_transport)
  97. def disconnect(self):
  98. if self._client_transport:
  99. self._client_transport = None
  100. self.client.close()
  101. if self._server_transport:
  102. self._server_transport = None
  103. self.server.close()
  104. def replicate(self):
  105. """Tell the master side of replication that something has happened, and then
  106. wait for the replication to occur.
  107. """
  108. self.streamer.on_notifier_poke()
  109. self.pump(0.1)
  110. def handle_http_replication_attempt(self) -> SynapseRequest:
  111. """Asserts that a connection attempt was made to the master HS on the
  112. HTTP replication port, then proxies it to the master HS object to be
  113. handled.
  114. Returns:
  115. The request object received by master HS.
  116. """
  117. # We should have an outbound connection attempt.
  118. clients = self.reactor.tcpClients
  119. self.assertEqual(len(clients), 1)
  120. (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0)
  121. self.assertEqual(host, "1.2.3.4")
  122. self.assertEqual(port, 8765)
  123. # Set up client side protocol
  124. client_protocol = client_factory.buildProtocol(None)
  125. request_factory = OneShotRequestFactory()
  126. # Set up the server side protocol
  127. channel = _PushHTTPChannel(self.reactor)
  128. channel.requestFactory = request_factory
  129. channel.site = self.site
  130. # Connect client to server and vice versa.
  131. client_to_server_transport = FakeTransport(
  132. channel, self.reactor, client_protocol
  133. )
  134. client_protocol.makeConnection(client_to_server_transport)
  135. server_to_client_transport = FakeTransport(
  136. client_protocol, self.reactor, channel
  137. )
  138. channel.makeConnection(server_to_client_transport)
  139. # The request will now be processed by `self.site` and the response
  140. # streamed back.
  141. self.reactor.advance(0)
  142. # We tear down the connection so it doesn't get reused without our
  143. # knowledge.
  144. server_to_client_transport.loseConnection()
  145. client_to_server_transport.loseConnection()
  146. return request_factory.request
  147. def assert_request_is_get_repl_stream_updates(
  148. self, request: SynapseRequest, stream_name: str
  149. ):
  150. """Asserts that the given request is a HTTP replication request for
  151. fetching updates for given stream.
  152. """
  153. self.assertRegex(
  154. request.path,
  155. br"^/_synapse/replication/get_repl_stream_updates/%s/[^/]+$"
  156. % (stream_name.encode("ascii"),),
  157. )
  158. self.assertEqual(request.method, b"GET")
  159. class BaseMultiWorkerStreamTestCase(unittest.HomeserverTestCase):
  160. """Base class for tests running multiple workers.
  161. Automatically handle HTTP replication requests from workers to master,
  162. unlike `BaseStreamTestCase`.
  163. """
  164. servlets = [] # type: List[Callable[[HomeServer, JsonResource], None]]
  165. def setUp(self):
  166. super().setUp()
  167. # build a replication server
  168. self.server_factory = ReplicationStreamProtocolFactory(self.hs)
  169. self.streamer = self.hs.get_replication_streamer()
  170. # Fake in memory Redis server that servers can connect to.
  171. self._redis_server = FakeRedisPubSubServer()
  172. # We may have an attempt to connect to redis for the external cache already.
  173. self.connect_any_redis_attempts()
  174. store = self.hs.get_datastore()
  175. self.database_pool = store.db_pool
  176. self.reactor.lookups["testserv"] = "1.2.3.4"
  177. self.reactor.lookups["localhost"] = "127.0.0.1"
  178. # A map from a HS instance to the associated HTTP Site to use for
  179. # handling inbound HTTP requests to that instance.
  180. self._hs_to_site = {self.hs: self.site}
  181. if self.hs.config.redis.redis_enabled:
  182. # Handle attempts to connect to fake redis server.
  183. self.reactor.add_tcp_client_callback(
  184. "localhost",
  185. 6379,
  186. self.connect_any_redis_attempts,
  187. )
  188. self.hs.get_tcp_replication().start_replication(self.hs)
  189. # When we see a connection attempt to the master replication listener we
  190. # automatically set up the connection. This is so that tests don't
  191. # manually have to go and explicitly set it up each time (plus sometimes
  192. # it is impossible to write the handling explicitly in the tests).
  193. #
  194. # Register the master replication listener:
  195. self.reactor.add_tcp_client_callback(
  196. "1.2.3.4",
  197. 8765,
  198. lambda: self._handle_http_replication_attempt(self.hs, 8765),
  199. )
  200. def create_test_resource(self):
  201. """Overrides `HomeserverTestCase.create_test_resource`."""
  202. # We override this so that it automatically registers all the HTTP
  203. # replication servlets, without having to explicitly do that in all
  204. # subclassses.
  205. resource = ReplicationRestResource(self.hs)
  206. for servlet in self.servlets:
  207. servlet(self.hs, resource)
  208. return resource
  209. def make_worker_hs(
  210. self, worker_app: str, extra_config: dict = {}, **kwargs
  211. ) -> HomeServer:
  212. """Make a new worker HS instance, correctly connecting replcation
  213. stream to the master HS.
  214. Args:
  215. worker_app: Type of worker, e.g. `synapse.app.federation_sender`.
  216. extra_config: Any extra config to use for this instances.
  217. **kwargs: Options that get passed to `self.setup_test_homeserver`,
  218. useful to e.g. pass some mocks for things like `federation_http_client`
  219. Returns:
  220. The new worker HomeServer instance.
  221. """
  222. config = self._get_worker_hs_config()
  223. config["worker_app"] = worker_app
  224. config.update(extra_config)
  225. worker_hs = self.setup_test_homeserver(
  226. homeserver_to_use=GenericWorkerServer,
  227. config=config,
  228. reactor=self.reactor,
  229. **kwargs,
  230. )
  231. # If the instance is in the `instance_map` config then workers may try
  232. # and send HTTP requests to it, so we register it with
  233. # `_handle_http_replication_attempt` like we do with the master HS.
  234. instance_name = worker_hs.get_instance_name()
  235. instance_loc = worker_hs.config.worker.instance_map.get(instance_name)
  236. if instance_loc:
  237. # Ensure the host is one that has a fake DNS entry.
  238. if instance_loc.host not in self.reactor.lookups:
  239. raise Exception(
  240. "Host does not have an IP for instance_map[%r].host = %r"
  241. % (
  242. instance_name,
  243. instance_loc.host,
  244. )
  245. )
  246. self.reactor.add_tcp_client_callback(
  247. self.reactor.lookups[instance_loc.host],
  248. instance_loc.port,
  249. lambda: self._handle_http_replication_attempt(
  250. worker_hs, instance_loc.port
  251. ),
  252. )
  253. store = worker_hs.get_datastore()
  254. store.db_pool._db_pool = self.database_pool._db_pool
  255. # Set up TCP replication between master and the new worker if we don't
  256. # have Redis support enabled.
  257. if not worker_hs.config.redis_enabled:
  258. repl_handler = ReplicationCommandHandler(worker_hs)
  259. client = ClientReplicationStreamProtocol(
  260. worker_hs,
  261. "client",
  262. "test",
  263. self.clock,
  264. repl_handler,
  265. )
  266. server = self.server_factory.buildProtocol(None)
  267. client_transport = FakeTransport(server, self.reactor)
  268. client.makeConnection(client_transport)
  269. server_transport = FakeTransport(client, self.reactor)
  270. server.makeConnection(server_transport)
  271. # Set up a resource for the worker
  272. resource = ReplicationRestResource(worker_hs)
  273. for servlet in self.servlets:
  274. servlet(worker_hs, resource)
  275. self._hs_to_site[worker_hs] = SynapseSite(
  276. logger_name="synapse.access.http.fake",
  277. site_tag="{}-{}".format(
  278. worker_hs.config.server.server_name, worker_hs.get_instance_name()
  279. ),
  280. config=worker_hs.config.server.listeners[0],
  281. resource=resource,
  282. server_version_string="1",
  283. )
  284. if worker_hs.config.redis.redis_enabled:
  285. worker_hs.get_tcp_replication().start_replication(worker_hs)
  286. return worker_hs
  287. def _get_worker_hs_config(self) -> dict:
  288. config = self.default_config()
  289. config["worker_replication_host"] = "testserv"
  290. config["worker_replication_http_port"] = "8765"
  291. return config
  292. def replicate(self):
  293. """Tell the master side of replication that something has happened, and then
  294. wait for the replication to occur.
  295. """
  296. self.streamer.on_notifier_poke()
  297. self.pump()
  298. def _handle_http_replication_attempt(self, hs, repl_port):
  299. """Handles a connection attempt to the given HS replication HTTP
  300. listener on the given port.
  301. """
  302. # We should have at least one outbound connection attempt, where the
  303. # last is one to the HTTP repication IP/port.
  304. clients = self.reactor.tcpClients
  305. self.assertGreaterEqual(len(clients), 1)
  306. (host, port, client_factory, _timeout, _bindAddress) = clients.pop()
  307. self.assertEqual(host, "1.2.3.4")
  308. self.assertEqual(port, repl_port)
  309. # Set up client side protocol
  310. client_protocol = client_factory.buildProtocol(None)
  311. request_factory = OneShotRequestFactory()
  312. # Set up the server side protocol
  313. channel = _PushHTTPChannel(self.reactor)
  314. channel.requestFactory = request_factory
  315. channel.site = self._hs_to_site[hs]
  316. # Connect client to server and vice versa.
  317. client_to_server_transport = FakeTransport(
  318. channel, self.reactor, client_protocol
  319. )
  320. client_protocol.makeConnection(client_to_server_transport)
  321. server_to_client_transport = FakeTransport(
  322. client_protocol, self.reactor, channel
  323. )
  324. channel.makeConnection(server_to_client_transport)
  325. # Note: at this point we've wired everything up, but we need to return
  326. # before the data starts flowing over the connections as this is called
  327. # inside `connecTCP` before the connection has been passed back to the
  328. # code that requested the TCP connection.
  329. def connect_any_redis_attempts(self):
  330. """If redis is enabled we need to deal with workers connecting to a
  331. redis server. We don't want to use a real Redis server so we use a
  332. fake one.
  333. """
  334. clients = self.reactor.tcpClients
  335. while clients:
  336. (host, port, client_factory, _timeout, _bindAddress) = clients.pop(0)
  337. self.assertEqual(host, "localhost")
  338. self.assertEqual(port, 6379)
  339. client_protocol = client_factory.buildProtocol(None)
  340. server_protocol = self._redis_server.buildProtocol(None)
  341. client_to_server_transport = FakeTransport(
  342. server_protocol, self.reactor, client_protocol
  343. )
  344. client_protocol.makeConnection(client_to_server_transport)
  345. server_to_client_transport = FakeTransport(
  346. client_protocol, self.reactor, server_protocol
  347. )
  348. server_protocol.makeConnection(server_to_client_transport)
  349. class TestReplicationDataHandler(GenericWorkerReplicationHandler):
  350. """Drop-in for ReplicationDataHandler which just collects RDATA rows"""
  351. def __init__(self, hs: HomeServer):
  352. super().__init__(hs)
  353. # list of received (stream_name, token, row) tuples
  354. self.received_rdata_rows = [] # type: List[Tuple[str, int, Any]]
  355. async def on_rdata(self, stream_name, instance_name, token, rows):
  356. await super().on_rdata(stream_name, instance_name, token, rows)
  357. for r in rows:
  358. self.received_rdata_rows.append((stream_name, token, r))
  359. @attr.s()
  360. class OneShotRequestFactory:
  361. """A simple request factory that generates a single `SynapseRequest` and
  362. stores it for future use. Can only be used once.
  363. """
  364. request = attr.ib(default=None)
  365. def __call__(self, *args, **kwargs):
  366. assert self.request is None
  367. self.request = SynapseRequest(*args, **kwargs)
  368. return self.request
  369. class _PushHTTPChannel(HTTPChannel):
  370. """A HTTPChannel that wraps pull producers to push producers.
  371. This is a hack to get around the fact that HTTPChannel transparently wraps a
  372. pull producer (which is what Synapse uses to reply to requests) with
  373. `_PullToPush` to convert it to a push producer. Unfortunately `_PullToPush`
  374. uses the standard reactor rather than letting us use our test reactor, which
  375. makes it very hard to test.
  376. """
  377. def __init__(self, reactor: IReactorTime):
  378. super().__init__()
  379. self.reactor = reactor
  380. self._pull_to_push_producer = None # type: Optional[_PullToPushProducer]
  381. def registerProducer(self, producer, streaming):
  382. # Convert pull producers to push producer.
  383. if not streaming:
  384. self._pull_to_push_producer = _PullToPushProducer(
  385. self.reactor, producer, self
  386. )
  387. producer = self._pull_to_push_producer
  388. super().registerProducer(producer, True)
  389. def unregisterProducer(self):
  390. if self._pull_to_push_producer:
  391. # We need to manually stop the _PullToPushProducer.
  392. self._pull_to_push_producer.stop()
  393. def checkPersistence(self, request, version):
  394. """Check whether the connection can be re-used"""
  395. # We hijack this to always say no for ease of wiring stuff up in
  396. # `handle_http_replication_attempt`.
  397. request.responseHeaders.setRawHeaders(b"connection", [b"close"])
  398. return False
  399. class _PullToPushProducer:
  400. """A push producer that wraps a pull producer."""
  401. def __init__(
  402. self, reactor: IReactorTime, producer: IPullProducer, consumer: IConsumer
  403. ):
  404. self._clock = Clock(reactor)
  405. self._producer = producer
  406. self._consumer = consumer
  407. # While running we use a looping call with a zero delay to call
  408. # resumeProducing on given producer.
  409. self._looping_call = None # type: Optional[LoopingCall]
  410. # We start writing next reactor tick.
  411. self._start_loop()
  412. def _start_loop(self):
  413. """Start the looping call to"""
  414. if not self._looping_call:
  415. # Start a looping call which runs every tick.
  416. self._looping_call = self._clock.looping_call(self._run_once, 0)
  417. def stop(self):
  418. """Stops calling resumeProducing."""
  419. if self._looping_call:
  420. self._looping_call.stop()
  421. self._looping_call = None
  422. def pauseProducing(self):
  423. """Implements IPushProducer"""
  424. self.stop()
  425. def resumeProducing(self):
  426. """Implements IPushProducer"""
  427. self._start_loop()
  428. def stopProducing(self):
  429. """Implements IPushProducer"""
  430. self.stop()
  431. self._producer.stopProducing()
  432. def _run_once(self):
  433. """Calls resumeProducing on producer once."""
  434. try:
  435. self._producer.resumeProducing()
  436. except Exception:
  437. logger.exception("Failed to call resumeProducing")
  438. try:
  439. self._consumer.unregisterProducer()
  440. except Exception:
  441. pass
  442. self.stopProducing()
  443. class FakeRedisPubSubServer:
  444. """A fake Redis server for pub/sub."""
  445. def __init__(self):
  446. self._subscribers = set()
  447. def add_subscriber(self, conn):
  448. """A connection has called SUBSCRIBE"""
  449. self._subscribers.add(conn)
  450. def remove_subscriber(self, conn):
  451. """A connection has called UNSUBSCRIBE"""
  452. self._subscribers.discard(conn)
  453. def publish(self, conn, channel, msg) -> int:
  454. """A connection want to publish a message to subscribers."""
  455. for sub in self._subscribers:
  456. sub.send(["message", channel, msg])
  457. return len(self._subscribers)
  458. def buildProtocol(self, addr):
  459. return FakeRedisPubSubProtocol(self)
  460. class FakeRedisPubSubProtocol(Protocol):
  461. """A connection from a client talking to the fake Redis server."""
  462. def __init__(self, server: FakeRedisPubSubServer):
  463. self._server = server
  464. self._reader = hiredis.Reader()
  465. def dataReceived(self, data):
  466. self._reader.feed(data)
  467. # We might get multiple messages in one packet.
  468. while True:
  469. msg = self._reader.gets()
  470. if msg is False:
  471. # No more messages.
  472. return
  473. if not isinstance(msg, list):
  474. # Inbound commands should always be a list
  475. raise Exception("Expected redis list")
  476. self.handle_command(msg[0], *msg[1:])
  477. def handle_command(self, command, *args):
  478. """Received a Redis command from the client."""
  479. # We currently only support pub/sub.
  480. if command == b"PUBLISH":
  481. channel, message = args
  482. num_subscribers = self._server.publish(self, channel, message)
  483. self.send(num_subscribers)
  484. elif command == b"SUBSCRIBE":
  485. (channel,) = args
  486. self._server.add_subscriber(self)
  487. self.send(["subscribe", channel, 1])
  488. # Since we use SET/GET to cache things we can safely no-op them.
  489. elif command == b"SET":
  490. self.send("OK")
  491. elif command == b"GET":
  492. self.send(None)
  493. else:
  494. raise Exception("Unknown command")
  495. def send(self, msg):
  496. """Send a message back to the client."""
  497. raw = self.encode(msg).encode("utf-8")
  498. self.transport.write(raw)
  499. self.transport.flush()
  500. def encode(self, obj):
  501. """Encode an object to its Redis format.
  502. Supports: strings/bytes, integers and list/tuples.
  503. """
  504. if isinstance(obj, bytes):
  505. # We assume bytes are just unicode strings.
  506. obj = obj.decode("utf-8")
  507. if obj is None:
  508. return "$-1\r\n"
  509. if isinstance(obj, str):
  510. return "${len}\r\n{str}\r\n".format(len=len(obj), str=obj)
  511. if isinstance(obj, int):
  512. return ":{val}\r\n".format(val=obj)
  513. if isinstance(obj, (list, tuple)):
  514. items = "".join(self.encode(a) for a in obj)
  515. return "*{len}\r\n{items}".format(len=len(obj), items=items)
  516. raise Exception("Unrecognized type for encoding redis: %r: %r", type(obj), obj)
  517. def connectionLost(self, reason):
  518. self._server.remove_subscriber(self)