test_multi_media_repo.py 9.9 KB

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