1
0

_base.py 22 KB

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