1
0

test_multi_media_repo.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. # Copyright 2020-2021 The Matrix.org Foundation C.I.C.
  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. import os
  16. from typing import Any, Optional, Tuple
  17. from twisted.internet.interfaces import IOpenSSLServerConnectionCreator
  18. from twisted.internet.protocol import Factory
  19. from twisted.protocols.tls import TLSMemoryBIOFactory, TLSMemoryBIOProtocol
  20. from twisted.test.proto_helpers import MemoryReactor
  21. from twisted.web.http import HTTPChannel
  22. from twisted.web.server import Request
  23. from synapse.rest import admin
  24. from synapse.rest.client import login
  25. from synapse.server import HomeServer
  26. from synapse.util import Clock
  27. from tests.http import TestServerTLSConnectionFactory, get_test_ca_cert_file
  28. from tests.replication._base import BaseMultiWorkerStreamTestCase
  29. from tests.server import FakeChannel, FakeTransport, make_request
  30. from tests.test_utils import SMALL_PNG
  31. logger = logging.getLogger(__name__)
  32. test_server_connection_factory: Optional[TestServerTLSConnectionFactory] = None
  33. class MediaRepoShardTestCase(BaseMultiWorkerStreamTestCase):
  34. """Checks running multiple media repos work correctly."""
  35. servlets = [
  36. admin.register_servlets_for_client_rest_resource,
  37. login.register_servlets,
  38. ]
  39. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  40. self.user_id = self.register_user("user", "pass")
  41. self.access_token = self.login("user", "pass")
  42. self.reactor.lookups["example.com"] = "1.2.3.4"
  43. def default_config(self) -> dict:
  44. conf = super().default_config()
  45. conf["federation_custom_ca_list"] = [get_test_ca_cert_file()]
  46. return conf
  47. def make_worker_hs(
  48. self, worker_app: str, extra_config: Optional[dict] = None, **kwargs: Any
  49. ) -> HomeServer:
  50. worker_hs = super().make_worker_hs(worker_app, extra_config, **kwargs)
  51. # Force the media paths onto the replication resource.
  52. worker_hs.get_media_repository_resource().register_servlets(
  53. self._hs_to_site[worker_hs].resource, worker_hs
  54. )
  55. return worker_hs
  56. def _get_media_req(
  57. self, hs: HomeServer, target: str, media_id: str
  58. ) -> Tuple[FakeChannel, Request]:
  59. """Request some remote media from the given HS by calling the download
  60. API.
  61. This then triggers an outbound request from the HS to the target.
  62. Returns:
  63. The channel for the *client* request and the *outbound* request for
  64. the media which the caller should respond to.
  65. """
  66. channel = make_request(
  67. self.reactor,
  68. self._hs_to_site[hs],
  69. "GET",
  70. f"/_matrix/media/r0/download/{target}/{media_id}",
  71. shorthand=False,
  72. access_token=self.access_token,
  73. await_result=False,
  74. )
  75. self.pump()
  76. clients = self.reactor.tcpClients
  77. self.assertGreaterEqual(len(clients), 1)
  78. (host, port, client_factory, _timeout, _bindAddress) = clients.pop()
  79. # build the test server
  80. server_tls_protocol = _build_test_server(get_connection_factory())
  81. # now, tell the client protocol factory to build the client protocol (it will be a
  82. # _WrappingProtocol, around a TLSMemoryBIOProtocol, around an
  83. # HTTP11ClientProtocol) and wire the output of said protocol up to the server via
  84. # a FakeTransport.
  85. #
  86. # Normally this would be done by the TCP socket code in Twisted, but we are
  87. # stubbing that out here.
  88. client_protocol = client_factory.buildProtocol(None)
  89. client_protocol.makeConnection(
  90. FakeTransport(server_tls_protocol, self.reactor, client_protocol)
  91. )
  92. # tell the server tls protocol to send its stuff back to the client, too
  93. server_tls_protocol.makeConnection(
  94. FakeTransport(client_protocol, self.reactor, server_tls_protocol)
  95. )
  96. # fish the test server back out of the server-side TLS protocol.
  97. http_server: HTTPChannel = server_tls_protocol.wrappedProtocol # type: ignore[assignment]
  98. # give the reactor a pump to get the TLS juices flowing.
  99. self.reactor.pump((0.1,))
  100. self.assertEqual(len(http_server.requests), 1)
  101. request = http_server.requests[0]
  102. self.assertEqual(request.method, b"GET")
  103. self.assertEqual(
  104. request.path,
  105. f"/_matrix/media/r0/download/{target}/{media_id}".encode(),
  106. )
  107. self.assertEqual(
  108. request.requestHeaders.getRawHeaders(b"host"), [target.encode("utf-8")]
  109. )
  110. return channel, request
  111. def test_basic(self) -> None:
  112. """Test basic fetching of remote media from a single worker."""
  113. hs1 = self.make_worker_hs("synapse.app.generic_worker")
  114. channel, request = self._get_media_req(hs1, "example.com:443", "ABC123")
  115. request.setResponseCode(200)
  116. request.responseHeaders.setRawHeaders(b"Content-Type", [b"text/plain"])
  117. request.write(b"Hello!")
  118. request.finish()
  119. self.pump(0.1)
  120. self.assertEqual(channel.code, 200)
  121. self.assertEqual(channel.result["body"], b"Hello!")
  122. def test_download_simple_file_race(self) -> None:
  123. """Test that fetching remote media from two different processes at the
  124. same time works.
  125. """
  126. hs1 = self.make_worker_hs("synapse.app.generic_worker")
  127. hs2 = self.make_worker_hs("synapse.app.generic_worker")
  128. start_count = self._count_remote_media()
  129. # Make two requests without responding to the outbound media requests.
  130. channel1, request1 = self._get_media_req(hs1, "example.com:443", "ABC123")
  131. channel2, request2 = self._get_media_req(hs2, "example.com:443", "ABC123")
  132. # Respond to the first outbound media request and check that the client
  133. # request is successful
  134. request1.setResponseCode(200)
  135. request1.responseHeaders.setRawHeaders(b"Content-Type", [b"text/plain"])
  136. request1.write(b"Hello!")
  137. request1.finish()
  138. self.pump(0.1)
  139. self.assertEqual(channel1.code, 200, channel1.result["body"])
  140. self.assertEqual(channel1.result["body"], b"Hello!")
  141. # Now respond to the second with the same content.
  142. request2.setResponseCode(200)
  143. request2.responseHeaders.setRawHeaders(b"Content-Type", [b"text/plain"])
  144. request2.write(b"Hello!")
  145. request2.finish()
  146. self.pump(0.1)
  147. self.assertEqual(channel2.code, 200, channel2.result["body"])
  148. self.assertEqual(channel2.result["body"], b"Hello!")
  149. # We expect only one new file to have been persisted.
  150. self.assertEqual(start_count + 1, self._count_remote_media())
  151. def test_download_image_race(self) -> None:
  152. """Test that fetching remote *images* from two different processes at
  153. the same time works.
  154. This checks that races generating thumbnails are handled correctly.
  155. """
  156. hs1 = self.make_worker_hs("synapse.app.generic_worker")
  157. hs2 = self.make_worker_hs("synapse.app.generic_worker")
  158. start_count = self._count_remote_thumbnails()
  159. channel1, request1 = self._get_media_req(hs1, "example.com:443", "PIC1")
  160. channel2, request2 = self._get_media_req(hs2, "example.com:443", "PIC1")
  161. request1.setResponseCode(200)
  162. request1.responseHeaders.setRawHeaders(b"Content-Type", [b"image/png"])
  163. request1.write(SMALL_PNG)
  164. request1.finish()
  165. self.pump(0.1)
  166. self.assertEqual(channel1.code, 200, channel1.result["body"])
  167. self.assertEqual(channel1.result["body"], SMALL_PNG)
  168. request2.setResponseCode(200)
  169. request2.responseHeaders.setRawHeaders(b"Content-Type", [b"image/png"])
  170. request2.write(SMALL_PNG)
  171. request2.finish()
  172. self.pump(0.1)
  173. self.assertEqual(channel2.code, 200, channel2.result["body"])
  174. self.assertEqual(channel2.result["body"], SMALL_PNG)
  175. # We expect only three new thumbnails to have been persisted.
  176. self.assertEqual(start_count + 3, self._count_remote_thumbnails())
  177. def _count_remote_media(self) -> int:
  178. """Count the number of files in our remote media directory."""
  179. path = os.path.join(
  180. self.hs.get_media_repository().primary_base_path, "remote_content"
  181. )
  182. return sum(len(files) for _, _, files in os.walk(path))
  183. def _count_remote_thumbnails(self) -> int:
  184. """Count the number of files in our remote thumbnails directory."""
  185. path = os.path.join(
  186. self.hs.get_media_repository().primary_base_path, "remote_thumbnail"
  187. )
  188. return sum(len(files) for _, _, files in os.walk(path))
  189. def get_connection_factory() -> TestServerTLSConnectionFactory:
  190. # this needs to happen once, but not until we are ready to run the first test
  191. global test_server_connection_factory
  192. if test_server_connection_factory is None:
  193. test_server_connection_factory = TestServerTLSConnectionFactory(
  194. sanlist=[b"DNS:example.com"]
  195. )
  196. return test_server_connection_factory
  197. def _build_test_server(
  198. connection_creator: IOpenSSLServerConnectionCreator,
  199. ) -> TLSMemoryBIOProtocol:
  200. """Construct a test server
  201. This builds an HTTP channel, wrapped with a TLSMemoryBIOProtocol
  202. Args:
  203. connection_creator: thing to build SSL connections
  204. Returns:
  205. TLSMemoryBIOProtocol
  206. """
  207. server_factory = Factory.forProtocol(HTTPChannel)
  208. # Request.finish expects the factory to have a 'log' method.
  209. server_factory.log = _log_request
  210. server_tls_factory = TLSMemoryBIOFactory(
  211. connection_creator, isClient=False, wrappedFactory=server_factory
  212. )
  213. return server_tls_factory.buildProtocol(None)
  214. def _log_request(request: Request) -> None:
  215. """Implements Factory.log, which is expected by Request.finish"""
  216. logger.info("Completed request %s", request)