You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

254 lines
9.4 KiB

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