2021-10-14 16:19:35 +03:00
|
|
|
# Copyright 2018-2021 The Matrix.org Foundation C.I.C.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
2018-07-09 09:09:20 +03:00
|
|
|
import json
|
2019-01-22 23:28:48 +03:00
|
|
|
import logging
|
Fix threadsafety in ThreadedMemoryReactorClock (#8497)
This could, very occasionally, cause:
```
tests.test_visibility.FilterEventsForServerTestCase.test_large_room
===============================================================================
[ERROR]
Traceback (most recent call last):
File "/src/tests/rest/media/v1/test_media_storage.py", line 86, in test_ensure_media_is_in_local_cache
self.wait_on_thread(x)
File "/src/tests/unittest.py", line 296, in wait_on_thread
self.reactor.advance(0.01)
File "/src/.tox/py35/lib/python3.5/site-packages/twisted/internet/task.py", line 826, in advance
self._sortCalls()
File "/src/.tox/py35/lib/python3.5/site-packages/twisted/internet/task.py", line 787, in _sortCalls
self.calls.sort(key=lambda a: a.getTime())
builtins.ValueError: list modified during sort
tests.rest.media.v1.test_media_storage.MediaStorageTests.test_ensure_media_is_in_local_cache
```
2020-10-09 19:22:25 +03:00
|
|
|
from collections import deque
|
2020-09-10 13:45:12 +03:00
|
|
|
from io import SEEK_END, BytesIO
|
2021-11-12 18:50:54 +03:00
|
|
|
from typing import (
|
|
|
|
AnyStr,
|
|
|
|
Callable,
|
|
|
|
Dict,
|
|
|
|
Iterable,
|
|
|
|
MutableMapping,
|
|
|
|
Optional,
|
|
|
|
Tuple,
|
|
|
|
Union,
|
|
|
|
)
|
2018-06-27 12:37:24 +03:00
|
|
|
|
2018-07-09 09:09:20 +03:00
|
|
|
import attr
|
Fix threadsafety in ThreadedMemoryReactorClock (#8497)
This could, very occasionally, cause:
```
tests.test_visibility.FilterEventsForServerTestCase.test_large_room
===============================================================================
[ERROR]
Traceback (most recent call last):
File "/src/tests/rest/media/v1/test_media_storage.py", line 86, in test_ensure_media_is_in_local_cache
self.wait_on_thread(x)
File "/src/tests/unittest.py", line 296, in wait_on_thread
self.reactor.advance(0.01)
File "/src/.tox/py35/lib/python3.5/site-packages/twisted/internet/task.py", line 826, in advance
self._sortCalls()
File "/src/.tox/py35/lib/python3.5/site-packages/twisted/internet/task.py", line 787, in _sortCalls
self.calls.sort(key=lambda a: a.getTime())
builtins.ValueError: list modified during sort
tests.rest.media.v1.test_media_storage.MediaStorageTests.test_ensure_media_is_in_local_cache
```
2020-10-09 19:22:25 +03:00
|
|
|
from typing_extensions import Deque
|
2018-09-13 17:15:51 +03:00
|
|
|
from zope.interface import implementer
|
2018-07-09 09:09:20 +03:00
|
|
|
|
2018-09-13 17:15:51 +03:00
|
|
|
from twisted.internet import address, threads, udp
|
2019-01-29 12:38:29 +03:00
|
|
|
from twisted.internet._resolver import SimpleResolverComplexifier
|
2021-08-27 18:33:41 +03:00
|
|
|
from twisted.internet.defer import Deferred, fail, maybeDeferred, succeed
|
2018-09-13 17:15:51 +03:00
|
|
|
from twisted.internet.error import DNSLookupError
|
2019-08-28 14:18:53 +03:00
|
|
|
from twisted.internet.interfaces import (
|
2021-08-27 18:33:41 +03:00
|
|
|
IAddress,
|
2021-03-26 19:49:46 +03:00
|
|
|
IHostnameResolver,
|
|
|
|
IProtocol,
|
|
|
|
IPullProducer,
|
|
|
|
IPushProducer,
|
2019-08-28 14:18:53 +03:00
|
|
|
IReactorPluggableNameResolver,
|
2021-09-24 13:01:25 +03:00
|
|
|
IReactorTime,
|
2019-08-28 14:18:53 +03:00
|
|
|
IResolverSimple,
|
2021-03-15 18:14:39 +03:00
|
|
|
ITransport,
|
2019-08-28 14:18:53 +03:00
|
|
|
)
|
2018-07-09 09:09:20 +03:00
|
|
|
from twisted.python.failure import Failure
|
2019-08-28 14:18:53 +03:00
|
|
|
from twisted.test.proto_helpers import AccumulatingProtocol, MemoryReactorClock
|
2018-11-16 00:55:58 +03:00
|
|
|
from twisted.web.http_headers import Headers
|
2020-11-14 01:39:09 +03:00
|
|
|
from twisted.web.resource import IResource
|
2021-10-14 16:19:35 +03:00
|
|
|
from twisted.web.server import Request, Site
|
2018-06-27 12:37:24 +03:00
|
|
|
|
|
|
|
from synapse.http.site import SynapseRequest
|
2021-10-14 16:19:35 +03:00
|
|
|
from synapse.types import JsonDict
|
2018-08-09 05:22:01 +03:00
|
|
|
from synapse.util import Clock
|
2018-07-09 09:09:20 +03:00
|
|
|
|
2018-06-27 12:37:24 +03:00
|
|
|
from tests.utils import setup_test_homeserver as _sth
|
|
|
|
|
2019-01-22 23:28:48 +03:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2018-06-27 12:37:24 +03:00
|
|
|
|
2018-11-02 16:19:23 +03:00
|
|
|
class TimedOutException(Exception):
|
|
|
|
"""
|
|
|
|
A web query timed out.
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
2018-06-27 12:37:24 +03:00
|
|
|
@attr.s
|
2020-09-04 13:54:56 +03:00
|
|
|
class FakeChannel:
|
2018-06-27 12:37:24 +03:00
|
|
|
"""
|
|
|
|
A fake Twisted Web Channel (the part that interfaces with the
|
|
|
|
wire).
|
|
|
|
"""
|
|
|
|
|
2021-03-26 19:49:46 +03:00
|
|
|
site = attr.ib(type=Union[Site, "FakeSite"])
|
2018-11-06 19:00:00 +03:00
|
|
|
_reactor = attr.ib()
|
2020-10-30 13:55:24 +03:00
|
|
|
result = attr.ib(type=dict, default=attr.Factory(dict))
|
2021-01-28 20:39:21 +03:00
|
|
|
_ip = attr.ib(type=str, default="127.0.0.1")
|
2021-07-13 13:52:58 +03:00
|
|
|
_producer: Optional[Union[IPullProducer, IPushProducer]] = None
|
2018-06-27 12:37:24 +03:00
|
|
|
|
|
|
|
@property
|
|
|
|
def json_body(self):
|
2021-01-13 23:21:55 +03:00
|
|
|
return json.loads(self.text_body)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def text_body(self) -> str:
|
|
|
|
"""The body of the result, utf-8-decoded.
|
|
|
|
|
|
|
|
Raises an exception if the request has not yet completed.
|
|
|
|
"""
|
|
|
|
if not self.is_finished:
|
|
|
|
raise Exception("Request not yet completed")
|
|
|
|
return self.result["body"].decode("utf8")
|
|
|
|
|
|
|
|
def is_finished(self) -> bool:
|
|
|
|
"""check if the response has been completely received"""
|
|
|
|
return self.result.get("done", False)
|
2018-08-09 05:22:01 +03:00
|
|
|
|
|
|
|
@property
|
|
|
|
def code(self):
|
|
|
|
if not self.result:
|
|
|
|
raise Exception("No result yet.")
|
|
|
|
return int(self.result["code"])
|
2018-06-27 12:37:24 +03:00
|
|
|
|
2018-11-16 00:55:58 +03:00
|
|
|
@property
|
2021-01-18 17:52:49 +03:00
|
|
|
def headers(self) -> Headers:
|
2018-11-16 00:55:58 +03:00
|
|
|
if not self.result:
|
|
|
|
raise Exception("No result yet.")
|
|
|
|
h = Headers()
|
|
|
|
for i in self.result["headers"]:
|
|
|
|
h.addRawHeader(*i)
|
|
|
|
return h
|
|
|
|
|
2018-06-27 12:37:24 +03:00
|
|
|
def writeHeaders(self, version, code, reason, headers):
|
|
|
|
self.result["version"] = version
|
|
|
|
self.result["code"] = code
|
|
|
|
self.result["reason"] = reason
|
|
|
|
self.result["headers"] = headers
|
|
|
|
|
|
|
|
def write(self, content):
|
2018-11-07 17:37:43 +03:00
|
|
|
assert isinstance(content, bytes), "Should be bytes! " + repr(content)
|
|
|
|
|
2018-06-27 12:37:24 +03:00
|
|
|
if "body" not in self.result:
|
|
|
|
self.result["body"] = b""
|
|
|
|
|
|
|
|
self.result["body"] += content
|
|
|
|
|
2018-08-15 16:43:41 +03:00
|
|
|
def registerProducer(self, producer, streaming):
|
|
|
|
self._producer = producer
|
2018-11-06 19:00:00 +03:00
|
|
|
self.producerStreaming = streaming
|
|
|
|
|
|
|
|
def _produce():
|
|
|
|
if self._producer:
|
|
|
|
self._producer.resumeProducing()
|
|
|
|
self._reactor.callLater(0.1, _produce)
|
|
|
|
|
|
|
|
if not streaming:
|
|
|
|
self._reactor.callLater(0.0, _produce)
|
2018-08-15 16:43:41 +03:00
|
|
|
|
|
|
|
def unregisterProducer(self):
|
|
|
|
if self._producer is None:
|
|
|
|
return
|
|
|
|
|
|
|
|
self._producer = None
|
|
|
|
|
2018-06-27 12:37:24 +03:00
|
|
|
def requestDone(self, _self):
|
|
|
|
self.result["done"] = True
|
|
|
|
|
|
|
|
def getPeer(self):
|
2018-08-23 20:33:04 +03:00
|
|
|
# We give an address so that getClientIP returns a non null entry,
|
|
|
|
# causing us to record the MAU
|
2021-01-28 20:39:21 +03:00
|
|
|
return address.IPv4Address("TCP", self._ip, 3423)
|
2018-06-27 12:37:24 +03:00
|
|
|
|
|
|
|
def getHost(self):
|
2021-02-26 17:02:06 +03:00
|
|
|
# this is called by Request.__init__ to configure Request.host.
|
|
|
|
return address.IPv4Address("TCP", "127.0.0.1", 8888)
|
|
|
|
|
|
|
|
def isSecure(self):
|
|
|
|
return False
|
2018-06-27 12:37:24 +03:00
|
|
|
|
|
|
|
@property
|
|
|
|
def transport(self):
|
|
|
|
return self
|
|
|
|
|
2021-06-17 18:23:11 +03:00
|
|
|
def await_result(self, timeout_ms: int = 1000) -> None:
|
2020-11-16 21:21:47 +03:00
|
|
|
"""
|
|
|
|
Wait until the request is finished.
|
|
|
|
"""
|
2021-06-17 18:23:11 +03:00
|
|
|
end_time = self._reactor.seconds() + timeout_ms / 1000.0
|
2020-11-16 21:21:47 +03:00
|
|
|
self._reactor.run()
|
|
|
|
|
2021-01-13 23:21:55 +03:00
|
|
|
while not self.is_finished():
|
2020-11-16 21:21:47 +03:00
|
|
|
# If there's a producer, tell it to resume producing so we get content
|
|
|
|
if self._producer:
|
|
|
|
self._producer.resumeProducing()
|
|
|
|
|
2021-06-17 18:23:11 +03:00
|
|
|
if self._reactor.seconds() > end_time:
|
2020-11-16 21:21:47 +03:00
|
|
|
raise TimedOutException("Timed out waiting for request to finish.")
|
|
|
|
|
|
|
|
self._reactor.advance(0.1)
|
|
|
|
|
2021-01-13 23:21:55 +03:00
|
|
|
def extract_cookies(self, cookies: MutableMapping[str, str]) -> None:
|
|
|
|
"""Process the contents of any Set-Cookie headers in the response
|
|
|
|
|
|
|
|
Any cookines found are added to the given dict
|
|
|
|
"""
|
2021-03-26 19:49:46 +03:00
|
|
|
headers = self.headers.getRawHeaders("Set-Cookie")
|
|
|
|
if not headers:
|
|
|
|
return
|
|
|
|
|
|
|
|
for h in headers:
|
2021-01-13 23:21:55 +03:00
|
|
|
parts = h.split(";")
|
|
|
|
k, v = parts[0].split("=", maxsplit=1)
|
|
|
|
cookies[k] = v
|
|
|
|
|
2018-06-27 12:37:24 +03:00
|
|
|
|
|
|
|
class FakeSite:
|
|
|
|
"""
|
|
|
|
A fake Twisted Web Site, with mocks of the extra things that
|
|
|
|
Synapse adds.
|
|
|
|
"""
|
|
|
|
|
|
|
|
server_version_string = b"1"
|
|
|
|
site_tag = "test"
|
2019-03-20 21:00:02 +03:00
|
|
|
access_logger = logging.getLogger("synapse.access.http.fake")
|
2018-06-27 12:37:24 +03:00
|
|
|
|
2021-09-24 13:01:25 +03:00
|
|
|
def __init__(self, resource: IResource, reactor: IReactorTime):
|
2020-11-14 01:39:09 +03:00
|
|
|
"""
|
|
|
|
|
|
|
|
Args:
|
|
|
|
resource: the resource to be used for rendering all requests
|
|
|
|
"""
|
|
|
|
self._resource = resource
|
2021-09-24 13:01:25 +03:00
|
|
|
self.reactor = reactor
|
2020-11-14 01:39:09 +03:00
|
|
|
|
|
|
|
def getResourceFor(self, request):
|
|
|
|
return self._resource
|
|
|
|
|
2018-06-27 12:37:24 +03:00
|
|
|
|
2018-11-05 21:53:44 +03:00
|
|
|
def make_request(
|
2018-11-06 19:00:00 +03:00
|
|
|
reactor,
|
2021-03-09 15:41:32 +03:00
|
|
|
site: Union[Site, FakeSite],
|
2021-10-14 16:19:35 +03:00
|
|
|
method: Union[bytes, str],
|
|
|
|
path: Union[bytes, str],
|
|
|
|
content: Union[bytes, str, JsonDict] = b"",
|
|
|
|
access_token: Optional[str] = None,
|
|
|
|
request: Request = SynapseRequest,
|
|
|
|
shorthand: bool = True,
|
|
|
|
federation_auth_origin: Optional[bytes] = None,
|
|
|
|
content_is_form: bool = False,
|
2020-11-16 01:47:54 +03:00
|
|
|
await_result: bool = True,
|
2021-11-12 18:50:54 +03:00
|
|
|
custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
|
2021-01-28 20:39:21 +03:00
|
|
|
client_ip: str = "127.0.0.1",
|
2020-12-15 17:44:04 +03:00
|
|
|
) -> FakeChannel:
|
2018-06-27 12:37:24 +03:00
|
|
|
"""
|
2020-11-16 01:47:54 +03:00
|
|
|
Make a web request using the given method, path and content, and render it
|
|
|
|
|
2020-12-15 17:44:04 +03:00
|
|
|
Returns the fake Channel object which records the response to the request.
|
2018-11-05 21:53:44 +03:00
|
|
|
|
|
|
|
Args:
|
2021-10-14 16:19:35 +03:00
|
|
|
reactor:
|
2020-11-16 01:47:54 +03:00
|
|
|
site: The twisted Site to use to render the request
|
2021-10-14 16:19:35 +03:00
|
|
|
method: The HTTP request method ("verb").
|
|
|
|
path: The HTTP path, suitably URL encoded (e.g. escaped UTF-8 & spaces and such).
|
|
|
|
content: The body of the request. JSON-encoded, if a str of bytes.
|
|
|
|
access_token: The access token to add as authorization for the request.
|
|
|
|
request: The request class to create.
|
2018-11-05 21:53:44 +03:00
|
|
|
shorthand: Whether to try and be helpful and prefix the given URL
|
2021-10-14 16:19:35 +03:00
|
|
|
with the usual REST API path, if it doesn't contain it.
|
|
|
|
federation_auth_origin: if set to not-None, we will add a fake
|
2019-03-04 13:05:39 +03:00
|
|
|
Authorization header pretenting to be the given server name.
|
2020-09-10 13:45:12 +03:00
|
|
|
content_is_form: Whether the content is URL encoded form data. Adds the
|
|
|
|
'Content-Type': 'application/x-www-form-urlencoded' header.
|
2020-11-16 01:47:54 +03:00
|
|
|
await_result: whether to wait for the request to complete rendering. If true,
|
|
|
|
will pump the reactor until the the renderer tells the channel the request
|
|
|
|
is finished.
|
2021-10-14 16:19:35 +03:00
|
|
|
custom_headers: (name, value) pairs to add as request headers
|
2021-01-28 20:39:21 +03:00
|
|
|
client_ip: The IP to use as the requesting IP. Useful for testing
|
|
|
|
ratelimiting.
|
|
|
|
|
2018-11-05 21:53:44 +03:00
|
|
|
Returns:
|
2020-12-15 17:44:04 +03:00
|
|
|
channel
|
2018-06-27 12:37:24 +03:00
|
|
|
"""
|
2018-08-09 05:22:01 +03:00
|
|
|
if not isinstance(method, bytes):
|
|
|
|
method = method.encode("ascii")
|
|
|
|
|
|
|
|
if not isinstance(path, bytes):
|
|
|
|
path = path.encode("ascii")
|
2018-06-27 12:37:24 +03:00
|
|
|
|
2018-11-05 21:53:44 +03:00
|
|
|
# Decorate it to be the full path, if we're using shorthand
|
2019-10-31 14:30:25 +03:00
|
|
|
if (
|
|
|
|
shorthand
|
|
|
|
and not path.startswith(b"/_matrix")
|
|
|
|
and not path.startswith(b"/_synapse")
|
|
|
|
):
|
2020-12-02 18:26:25 +03:00
|
|
|
if path.startswith(b"/"):
|
|
|
|
path = path[1:]
|
2018-07-17 13:43:18 +03:00
|
|
|
path = b"/_matrix/client/r0/" + path
|
|
|
|
|
2018-11-16 00:55:58 +03:00
|
|
|
if not path.startswith(b"/"):
|
|
|
|
path = b"/" + path
|
|
|
|
|
2020-11-14 02:48:25 +03:00
|
|
|
if isinstance(content, dict):
|
|
|
|
content = json.dumps(content).encode("utf8")
|
2020-06-16 15:51:47 +03:00
|
|
|
if isinstance(content, str):
|
2018-06-27 12:37:24 +03:00
|
|
|
content = content.encode("utf8")
|
|
|
|
|
2021-01-28 20:39:21 +03:00
|
|
|
channel = FakeChannel(site, reactor, ip=client_ip)
|
2018-06-27 12:37:24 +03:00
|
|
|
|
2021-09-24 13:01:25 +03:00
|
|
|
req = request(channel, site)
|
2018-06-27 12:37:24 +03:00
|
|
|
req.content = BytesIO(content)
|
2020-09-10 13:45:12 +03:00
|
|
|
# Twisted expects to be at the end of the content when parsing the request.
|
|
|
|
req.content.seek(SEEK_END)
|
2018-08-23 20:33:04 +03:00
|
|
|
|
|
|
|
if access_token:
|
2018-10-30 15:55:43 +03:00
|
|
|
req.requestHeaders.addRawHeader(
|
|
|
|
b"Authorization", b"Bearer " + access_token.encode("ascii")
|
|
|
|
)
|
2018-08-23 20:33:04 +03:00
|
|
|
|
2019-03-04 13:05:39 +03:00
|
|
|
if federation_auth_origin is not None:
|
|
|
|
req.requestHeaders.addRawHeader(
|
2019-05-10 08:12:11 +03:00
|
|
|
b"Authorization",
|
|
|
|
b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin,),
|
2019-03-04 13:05:39 +03:00
|
|
|
)
|
|
|
|
|
2018-09-20 13:14:34 +03:00
|
|
|
if content:
|
2020-09-10 13:45:12 +03:00
|
|
|
if content_is_form:
|
|
|
|
req.requestHeaders.addRawHeader(
|
|
|
|
b"Content-Type", b"application/x-www-form-urlencoded"
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
# Assume the body is JSON
|
|
|
|
req.requestHeaders.addRawHeader(b"Content-Type", b"application/json")
|
2018-09-20 13:14:34 +03:00
|
|
|
|
2020-11-16 17:45:22 +03:00
|
|
|
if custom_headers:
|
|
|
|
for k, v in custom_headers:
|
|
|
|
req.requestHeaders.addRawHeader(k, v)
|
|
|
|
|
2020-12-01 03:15:36 +03:00
|
|
|
req.parseCookies()
|
2018-06-27 12:37:24 +03:00
|
|
|
req.requestReceived(method, path, b"1.1")
|
|
|
|
|
2020-11-16 01:47:54 +03:00
|
|
|
if await_result:
|
|
|
|
channel.await_result()
|
|
|
|
|
2020-12-15 17:44:04 +03:00
|
|
|
return channel
|
2018-06-27 12:37:24 +03:00
|
|
|
|
|
|
|
|
2018-09-13 17:15:51 +03:00
|
|
|
@implementer(IReactorPluggableNameResolver)
|
2018-06-27 12:37:24 +03:00
|
|
|
class ThreadedMemoryReactorClock(MemoryReactorClock):
|
|
|
|
"""
|
|
|
|
A MemoryReactorClock that supports callFromThread.
|
|
|
|
"""
|
2018-08-10 16:54:09 +03:00
|
|
|
|
2018-09-13 17:15:51 +03:00
|
|
|
def __init__(self):
|
2019-05-13 23:01:14 +03:00
|
|
|
self.threadpool = ThreadPool(self)
|
|
|
|
|
2021-09-30 14:51:47 +03:00
|
|
|
self._tcp_callbacks: Dict[Tuple[str, int], Callable] = {}
|
2018-09-13 17:15:51 +03:00
|
|
|
self._udp = []
|
2021-07-13 13:52:58 +03:00
|
|
|
self.lookups: Dict[str, str] = {}
|
|
|
|
self._thread_callbacks: Deque[Callable[[], None]] = deque()
|
|
|
|
|
|
|
|
lookups = self.lookups
|
2019-01-29 12:38:29 +03:00
|
|
|
|
|
|
|
@implementer(IResolverSimple)
|
2020-09-04 13:54:56 +03:00
|
|
|
class FakeResolver:
|
2019-01-29 12:38:29 +03:00
|
|
|
def getHostByName(self, name, timeout=None):
|
|
|
|
if name not in lookups:
|
2019-05-10 08:12:11 +03:00
|
|
|
return fail(DNSLookupError("OH NO: unknown %s" % (name,)))
|
2019-01-29 12:38:29 +03:00
|
|
|
return succeed(lookups[name])
|
|
|
|
|
|
|
|
self.nameResolver = SimpleResolverComplexifier(FakeResolver())
|
2020-09-18 16:56:44 +03:00
|
|
|
super().__init__()
|
2018-09-13 17:15:51 +03:00
|
|
|
|
2021-03-26 19:49:46 +03:00
|
|
|
def installNameResolver(self, resolver: IHostnameResolver) -> IHostnameResolver:
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
2018-09-13 17:15:51 +03:00
|
|
|
def listenUDP(self, port, protocol, interface="", maxPacketSize=8196):
|
|
|
|
p = udp.Port(port, protocol, interface, maxPacketSize, self)
|
|
|
|
p.startListening()
|
|
|
|
self._udp.append(p)
|
|
|
|
return p
|
|
|
|
|
2018-06-27 12:37:24 +03:00
|
|
|
def callFromThread(self, callback, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Make the callback fire in the next reactor iteration.
|
|
|
|
"""
|
Fix threadsafety in ThreadedMemoryReactorClock (#8497)
This could, very occasionally, cause:
```
tests.test_visibility.FilterEventsForServerTestCase.test_large_room
===============================================================================
[ERROR]
Traceback (most recent call last):
File "/src/tests/rest/media/v1/test_media_storage.py", line 86, in test_ensure_media_is_in_local_cache
self.wait_on_thread(x)
File "/src/tests/unittest.py", line 296, in wait_on_thread
self.reactor.advance(0.01)
File "/src/.tox/py35/lib/python3.5/site-packages/twisted/internet/task.py", line 826, in advance
self._sortCalls()
File "/src/.tox/py35/lib/python3.5/site-packages/twisted/internet/task.py", line 787, in _sortCalls
self.calls.sort(key=lambda a: a.getTime())
builtins.ValueError: list modified during sort
tests.rest.media.v1.test_media_storage.MediaStorageTests.test_ensure_media_is_in_local_cache
```
2020-10-09 19:22:25 +03:00
|
|
|
cb = lambda: callback(*args, **kwargs)
|
|
|
|
# it's not safe to call callLater() here, so we append the callback to a
|
|
|
|
# separate queue.
|
|
|
|
self._thread_callbacks.append(cb)
|
2018-06-27 12:37:24 +03:00
|
|
|
|
2019-05-13 23:01:14 +03:00
|
|
|
def getThreadPool(self):
|
|
|
|
return self.threadpool
|
|
|
|
|
2021-09-30 14:51:47 +03:00
|
|
|
def add_tcp_client_callback(self, host: str, port: int, callback: Callable):
|
2020-07-15 17:27:35 +03:00
|
|
|
"""Add a callback that will be invoked when we receive a connection
|
|
|
|
attempt to the given IP/port using `connectTCP`.
|
|
|
|
|
|
|
|
Note that the callback gets run before we return the connection to the
|
|
|
|
client, which means callbacks cannot block while waiting for writes.
|
|
|
|
"""
|
|
|
|
self._tcp_callbacks[(host, port)] = callback
|
|
|
|
|
2021-09-30 14:51:47 +03:00
|
|
|
def connectTCP(self, host: str, port: int, factory, timeout=30, bindAddress=None):
|
2020-07-15 17:27:35 +03:00
|
|
|
"""Fake L{IReactorTCP.connectTCP}."""
|
|
|
|
|
|
|
|
conn = super().connectTCP(
|
|
|
|
host, port, factory, timeout=timeout, bindAddress=None
|
|
|
|
)
|
|
|
|
|
|
|
|
callback = self._tcp_callbacks.get((host, port))
|
|
|
|
if callback:
|
|
|
|
callback()
|
|
|
|
|
|
|
|
return conn
|
|
|
|
|
Fix threadsafety in ThreadedMemoryReactorClock (#8497)
This could, very occasionally, cause:
```
tests.test_visibility.FilterEventsForServerTestCase.test_large_room
===============================================================================
[ERROR]
Traceback (most recent call last):
File "/src/tests/rest/media/v1/test_media_storage.py", line 86, in test_ensure_media_is_in_local_cache
self.wait_on_thread(x)
File "/src/tests/unittest.py", line 296, in wait_on_thread
self.reactor.advance(0.01)
File "/src/.tox/py35/lib/python3.5/site-packages/twisted/internet/task.py", line 826, in advance
self._sortCalls()
File "/src/.tox/py35/lib/python3.5/site-packages/twisted/internet/task.py", line 787, in _sortCalls
self.calls.sort(key=lambda a: a.getTime())
builtins.ValueError: list modified during sort
tests.rest.media.v1.test_media_storage.MediaStorageTests.test_ensure_media_is_in_local_cache
```
2020-10-09 19:22:25 +03:00
|
|
|
def advance(self, amount):
|
|
|
|
# first advance our reactor's time, and run any "callLater" callbacks that
|
|
|
|
# makes ready
|
|
|
|
super().advance(amount)
|
|
|
|
|
|
|
|
# now run any "callFromThread" callbacks
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
callback = self._thread_callbacks.popleft()
|
|
|
|
except IndexError:
|
|
|
|
break
|
|
|
|
callback()
|
|
|
|
|
|
|
|
# check for more "callLater" callbacks added by the thread callback
|
|
|
|
# This isn't required in a regular reactor, but it ends up meaning that
|
|
|
|
# our database queries can complete in a single call to `advance` [1] which
|
|
|
|
# simplifies tests.
|
|
|
|
#
|
|
|
|
# [1]: we replace the threadpool backing the db connection pool with a
|
|
|
|
# mock ThreadPool which doesn't really use threads; but we still use
|
|
|
|
# reactor.callFromThread to feed results back from the db functions to the
|
|
|
|
# main thread.
|
|
|
|
super().advance(0)
|
|
|
|
|
2019-05-13 23:01:14 +03:00
|
|
|
|
|
|
|
class ThreadPool:
|
|
|
|
"""
|
|
|
|
Threadless thread pool.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, reactor):
|
|
|
|
self._reactor = reactor
|
|
|
|
|
|
|
|
def start(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def stop(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def callInThreadWithCallback(self, onResult, function, *args, **kwargs):
|
|
|
|
def _(res):
|
|
|
|
if isinstance(res, Failure):
|
|
|
|
onResult(False, res)
|
|
|
|
else:
|
|
|
|
onResult(True, res)
|
|
|
|
|
|
|
|
d = Deferred()
|
|
|
|
d.addCallback(lambda x: function(*args, **kwargs))
|
|
|
|
d.addBoth(_)
|
|
|
|
self._reactor.callLater(0, d.callback, True)
|
|
|
|
return d
|
|
|
|
|
2018-06-27 12:37:24 +03:00
|
|
|
|
2018-08-13 09:47:46 +03:00
|
|
|
def setup_test_homeserver(cleanup_func, *args, **kwargs):
|
2018-06-27 12:37:24 +03:00
|
|
|
"""
|
|
|
|
Set up a synchronous test server, driven by the reactor used by
|
|
|
|
the homeserver.
|
|
|
|
"""
|
2019-12-18 13:45:12 +03:00
|
|
|
server = _sth(cleanup_func, *args, **kwargs)
|
2018-08-13 09:47:46 +03:00
|
|
|
|
2018-06-27 12:37:24 +03:00
|
|
|
# Make the thread pool synchronous.
|
2019-12-18 13:45:12 +03:00
|
|
|
clock = server.get_clock()
|
|
|
|
|
|
|
|
for database in server.get_datastores().databases:
|
|
|
|
pool = database._db_pool
|
|
|
|
|
|
|
|
def runWithConnection(func, *args, **kwargs):
|
|
|
|
return threads.deferToThreadPool(
|
|
|
|
pool._reactor,
|
|
|
|
pool.threadpool,
|
|
|
|
pool._runWithConnection,
|
|
|
|
func,
|
|
|
|
*args,
|
|
|
|
**kwargs,
|
|
|
|
)
|
|
|
|
|
|
|
|
def runInteraction(interaction, *args, **kwargs):
|
|
|
|
return threads.deferToThreadPool(
|
|
|
|
pool._reactor,
|
|
|
|
pool.threadpool,
|
|
|
|
pool._runInteraction,
|
|
|
|
interaction,
|
|
|
|
*args,
|
|
|
|
**kwargs,
|
|
|
|
)
|
2018-06-27 12:37:24 +03:00
|
|
|
|
2019-03-04 13:05:39 +03:00
|
|
|
pool.runWithConnection = runWithConnection
|
|
|
|
pool.runInteraction = runInteraction
|
2019-05-13 23:01:14 +03:00
|
|
|
pool.threadpool = ThreadPool(clock._reactor)
|
2019-03-04 13:05:39 +03:00
|
|
|
pool.running = True
|
2019-12-18 13:45:12 +03:00
|
|
|
|
2020-10-02 17:09:31 +03:00
|
|
|
# We've just changed the Databases to run DB transactions on the same
|
|
|
|
# thread, so we need to disable the dedicated thread behaviour.
|
|
|
|
server.get_datastores().main.USE_DEDICATED_DB_THREADS_FOR_EVENT_FETCHING = False
|
|
|
|
|
2019-12-18 13:45:12 +03:00
|
|
|
return server
|
2018-08-09 05:22:01 +03:00
|
|
|
|
|
|
|
|
2021-09-30 14:51:47 +03:00
|
|
|
def get_clock() -> Tuple[ThreadedMemoryReactorClock, Clock]:
|
2018-08-09 05:22:01 +03:00
|
|
|
clock = ThreadedMemoryReactorClock()
|
|
|
|
hs_clock = Clock(clock)
|
2019-08-30 18:28:26 +03:00
|
|
|
return clock, hs_clock
|
2018-09-18 20:17:15 +03:00
|
|
|
|
|
|
|
|
2021-03-15 18:14:39 +03:00
|
|
|
@implementer(ITransport)
|
2019-01-23 14:25:36 +03:00
|
|
|
@attr.s(cmp=False)
|
2020-09-04 13:54:56 +03:00
|
|
|
class FakeTransport:
|
2018-09-18 20:17:15 +03:00
|
|
|
"""
|
|
|
|
A twisted.internet.interfaces.ITransport implementation which sends all its data
|
|
|
|
straight into an IProtocol object: it exists to connect two IProtocols together.
|
|
|
|
|
|
|
|
To use it, instantiate it with the receiving IProtocol, and then pass it to the
|
|
|
|
sending IProtocol's makeConnection method:
|
|
|
|
|
|
|
|
server = HTTPChannel()
|
|
|
|
client.makeConnection(FakeTransport(server, self.reactor))
|
|
|
|
|
|
|
|
If you want bidirectional communication, you'll need two instances.
|
|
|
|
"""
|
|
|
|
|
|
|
|
other = attr.ib()
|
|
|
|
"""The Protocol object which will receive any data written to this transport.
|
|
|
|
|
|
|
|
:type: twisted.internet.interfaces.IProtocol
|
|
|
|
"""
|
|
|
|
|
|
|
|
_reactor = attr.ib()
|
|
|
|
"""Test reactor
|
|
|
|
|
|
|
|
:type: twisted.internet.interfaces.IReactorTime
|
|
|
|
"""
|
|
|
|
|
2019-01-29 16:53:02 +03:00
|
|
|
_protocol = attr.ib(default=None)
|
|
|
|
"""The Protocol which is producing data for this transport. Optional, but if set
|
|
|
|
will get called back for connectionLost() notifications etc.
|
|
|
|
"""
|
|
|
|
|
2021-08-27 18:33:41 +03:00
|
|
|
_peer_address: Optional[IAddress] = attr.ib(default=None)
|
|
|
|
"""The value to be returend by getPeer"""
|
|
|
|
|
2018-09-18 20:17:15 +03:00
|
|
|
disconnecting = False
|
2019-01-30 13:55:25 +03:00
|
|
|
disconnected = False
|
2019-11-25 19:45:50 +03:00
|
|
|
connected = True
|
2018-09-18 20:17:15 +03:00
|
|
|
buffer = attr.ib(default=b"")
|
|
|
|
producer = attr.ib(default=None)
|
2019-04-02 14:42:39 +03:00
|
|
|
autoflush = attr.ib(default=True)
|
2018-09-18 20:17:15 +03:00
|
|
|
|
|
|
|
def getPeer(self):
|
2021-08-27 18:33:41 +03:00
|
|
|
return self._peer_address
|
2018-09-18 20:17:15 +03:00
|
|
|
|
|
|
|
def getHost(self):
|
|
|
|
return None
|
|
|
|
|
2019-01-29 16:53:02 +03:00
|
|
|
def loseConnection(self, reason=None):
|
|
|
|
if not self.disconnecting:
|
2019-01-30 13:55:25 +03:00
|
|
|
logger.info("FakeTransport: loseConnection(%s)", reason)
|
2019-01-29 16:53:02 +03:00
|
|
|
self.disconnecting = True
|
|
|
|
if self._protocol:
|
|
|
|
self._protocol.connectionLost(reason)
|
2019-11-01 17:07:44 +03:00
|
|
|
|
|
|
|
# if we still have data to write, delay until that is done
|
|
|
|
if self.buffer:
|
|
|
|
logger.info(
|
|
|
|
"FakeTransport: Delaying disconnect until buffer is flushed"
|
|
|
|
)
|
|
|
|
else:
|
2019-11-25 19:45:50 +03:00
|
|
|
self.connected = False
|
2019-11-01 17:07:44 +03:00
|
|
|
self.disconnected = True
|
2018-09-18 20:17:15 +03:00
|
|
|
|
|
|
|
def abortConnection(self):
|
2019-01-30 13:55:25 +03:00
|
|
|
logger.info("FakeTransport: abortConnection()")
|
2019-11-01 17:07:44 +03:00
|
|
|
|
|
|
|
if not self.disconnecting:
|
|
|
|
self.disconnecting = True
|
|
|
|
if self._protocol:
|
|
|
|
self._protocol.connectionLost(None)
|
|
|
|
|
|
|
|
self.disconnected = True
|
2018-09-18 20:17:15 +03:00
|
|
|
|
|
|
|
def pauseProducing(self):
|
2018-12-21 17:56:13 +03:00
|
|
|
if not self.producer:
|
|
|
|
return
|
|
|
|
|
2018-09-18 20:17:15 +03:00
|
|
|
self.producer.pauseProducing()
|
|
|
|
|
2018-12-21 17:56:13 +03:00
|
|
|
def resumeProducing(self):
|
|
|
|
if not self.producer:
|
|
|
|
return
|
|
|
|
self.producer.resumeProducing()
|
|
|
|
|
2018-09-18 20:17:15 +03:00
|
|
|
def unregisterProducer(self):
|
|
|
|
if not self.producer:
|
|
|
|
return
|
|
|
|
|
|
|
|
self.producer = None
|
|
|
|
|
|
|
|
def registerProducer(self, producer, streaming):
|
|
|
|
self.producer = producer
|
|
|
|
self.producerStreaming = streaming
|
|
|
|
|
|
|
|
def _produce():
|
2021-08-27 18:33:41 +03:00
|
|
|
if not self.producer:
|
|
|
|
# we've been unregistered
|
|
|
|
return
|
|
|
|
# some implementations of IProducer (for example, FileSender)
|
|
|
|
# don't return a deferred.
|
|
|
|
d = maybeDeferred(self.producer.resumeProducing)
|
2018-09-18 20:17:15 +03:00
|
|
|
d.addCallback(lambda x: self._reactor.callLater(0.1, _produce))
|
|
|
|
|
|
|
|
if not streaming:
|
|
|
|
self._reactor.callLater(0.0, _produce)
|
|
|
|
|
|
|
|
def write(self, byt):
|
2019-11-01 17:07:44 +03:00
|
|
|
if self.disconnecting:
|
|
|
|
raise Exception("Writing to disconnecting FakeTransport")
|
|
|
|
|
2018-09-18 20:17:15 +03:00
|
|
|
self.buffer = self.buffer + byt
|
|
|
|
|
2019-01-22 23:28:48 +03:00
|
|
|
# always actually do the write asynchronously. Some protocols (notably the
|
|
|
|
# TLSMemoryBIOProtocol) get very confused if a read comes back while they are
|
|
|
|
# still doing a write. Doing a callLater here breaks the cycle.
|
2019-04-02 14:42:39 +03:00
|
|
|
if self.autoflush:
|
|
|
|
self._reactor.callLater(0.0, self.flush)
|
2018-09-18 20:17:15 +03:00
|
|
|
|
|
|
|
def writeSequence(self, seq):
|
|
|
|
for x in seq:
|
|
|
|
self.write(x)
|
2019-04-02 14:42:39 +03:00
|
|
|
|
|
|
|
def flush(self, maxbytes=None):
|
|
|
|
if not self.buffer:
|
|
|
|
# nothing to do. Don't write empty buffers: it upsets the
|
|
|
|
# TLSMemoryBIOProtocol
|
|
|
|
return
|
|
|
|
|
|
|
|
if self.disconnected:
|
|
|
|
return
|
|
|
|
|
|
|
|
if maxbytes is not None:
|
|
|
|
to_write = self.buffer[:maxbytes]
|
|
|
|
else:
|
|
|
|
to_write = self.buffer
|
|
|
|
|
|
|
|
logger.info("%s->%s: %s", self._protocol, self.other, to_write)
|
|
|
|
|
|
|
|
try:
|
|
|
|
self.other.dataReceived(to_write)
|
|
|
|
except Exception as e:
|
2020-07-15 17:27:35 +03:00
|
|
|
logger.exception("Exception writing to protocol: %s", e)
|
2019-04-02 14:42:39 +03:00
|
|
|
return
|
|
|
|
|
2019-05-10 08:12:11 +03:00
|
|
|
self.buffer = self.buffer[len(to_write) :]
|
2019-04-02 14:42:39 +03:00
|
|
|
if self.buffer and self.autoflush:
|
|
|
|
self._reactor.callLater(0.0, self.flush)
|
2019-08-28 14:18:53 +03:00
|
|
|
|
2019-11-01 17:07:44 +03:00
|
|
|
if not self.buffer and self.disconnecting:
|
|
|
|
logger.info("FakeTransport: Buffer now empty, completing disconnect")
|
|
|
|
self.disconnected = True
|
|
|
|
|
2019-08-28 14:18:53 +03:00
|
|
|
|
2021-03-26 19:49:46 +03:00
|
|
|
def connect_client(
|
|
|
|
reactor: ThreadedMemoryReactorClock, client_id: int
|
|
|
|
) -> Tuple[IProtocol, AccumulatingProtocol]:
|
2019-08-28 14:18:53 +03:00
|
|
|
"""
|
|
|
|
Connect a client to a fake TCP transport.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
reactor
|
|
|
|
factory: The connecting factory to build.
|
|
|
|
"""
|
2020-10-29 14:27:37 +03:00
|
|
|
factory = reactor.tcpClients.pop(client_id)[2]
|
2019-08-28 14:18:53 +03:00
|
|
|
client = factory.buildProtocol(None)
|
|
|
|
server = AccumulatingProtocol()
|
|
|
|
server.makeConnection(FakeTransport(client, reactor))
|
|
|
|
client.makeConnection(FakeTransport(server, reactor))
|
|
|
|
|
|
|
|
return client, server
|