test_multi_media_repo.py 9.9 KB

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