server.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. # Copyright 2018-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 hashlib
  15. import json
  16. import logging
  17. import os
  18. import os.path
  19. import time
  20. import uuid
  21. import warnings
  22. from collections import deque
  23. from io import SEEK_END, BytesIO
  24. from typing import (
  25. AnyStr,
  26. Callable,
  27. Dict,
  28. Iterable,
  29. MutableMapping,
  30. Optional,
  31. Tuple,
  32. Type,
  33. Union,
  34. )
  35. from unittest.mock import Mock
  36. import attr
  37. from typing_extensions import Deque
  38. from zope.interface import implementer
  39. from twisted.internet import address, threads, udp
  40. from twisted.internet._resolver import SimpleResolverComplexifier
  41. from twisted.internet.defer import Deferred, fail, maybeDeferred, succeed
  42. from twisted.internet.error import DNSLookupError
  43. from twisted.internet.interfaces import (
  44. IAddress,
  45. IHostnameResolver,
  46. IProtocol,
  47. IPullProducer,
  48. IPushProducer,
  49. IReactorPluggableNameResolver,
  50. IReactorTime,
  51. IResolverSimple,
  52. ITransport,
  53. )
  54. from twisted.python.failure import Failure
  55. from twisted.test.proto_helpers import AccumulatingProtocol, MemoryReactorClock
  56. from twisted.web.http_headers import Headers
  57. from twisted.web.resource import IResource
  58. from twisted.web.server import Request, Site
  59. from synapse.config.database import DatabaseConnectionConfig
  60. from synapse.http.site import SynapseRequest
  61. from synapse.server import HomeServer
  62. from synapse.storage import DataStore
  63. from synapse.storage.engines import PostgresEngine, create_engine
  64. from synapse.types import JsonDict
  65. from synapse.util import Clock
  66. from tests.utils import (
  67. LEAVE_DB,
  68. POSTGRES_BASE_DB,
  69. POSTGRES_HOST,
  70. POSTGRES_PASSWORD,
  71. POSTGRES_USER,
  72. SQLITE_PERSIST_DB,
  73. USE_POSTGRES_FOR_TESTS,
  74. MockClock,
  75. default_config,
  76. )
  77. logger = logging.getLogger(__name__)
  78. class TimedOutException(Exception):
  79. """
  80. A web query timed out.
  81. """
  82. @attr.s
  83. class FakeChannel:
  84. """
  85. A fake Twisted Web Channel (the part that interfaces with the
  86. wire).
  87. """
  88. site = attr.ib(type=Union[Site, "FakeSite"])
  89. _reactor = attr.ib()
  90. result = attr.ib(type=dict, default=attr.Factory(dict))
  91. _ip = attr.ib(type=str, default="127.0.0.1")
  92. _producer: Optional[Union[IPullProducer, IPushProducer]] = None
  93. @property
  94. def json_body(self):
  95. return json.loads(self.text_body)
  96. @property
  97. def text_body(self) -> str:
  98. """The body of the result, utf-8-decoded.
  99. Raises an exception if the request has not yet completed.
  100. """
  101. if not self.is_finished:
  102. raise Exception("Request not yet completed")
  103. return self.result["body"].decode("utf8")
  104. def is_finished(self) -> bool:
  105. """check if the response has been completely received"""
  106. return self.result.get("done", False)
  107. @property
  108. def code(self):
  109. if not self.result:
  110. raise Exception("No result yet.")
  111. return int(self.result["code"])
  112. @property
  113. def headers(self) -> Headers:
  114. if not self.result:
  115. raise Exception("No result yet.")
  116. h = Headers()
  117. for i in self.result["headers"]:
  118. h.addRawHeader(*i)
  119. return h
  120. def writeHeaders(self, version, code, reason, headers):
  121. self.result["version"] = version
  122. self.result["code"] = code
  123. self.result["reason"] = reason
  124. self.result["headers"] = headers
  125. def write(self, content):
  126. assert isinstance(content, bytes), "Should be bytes! " + repr(content)
  127. if "body" not in self.result:
  128. self.result["body"] = b""
  129. self.result["body"] += content
  130. def registerProducer(self, producer, streaming):
  131. self._producer = producer
  132. self.producerStreaming = streaming
  133. def _produce():
  134. if self._producer:
  135. self._producer.resumeProducing()
  136. self._reactor.callLater(0.1, _produce)
  137. if not streaming:
  138. self._reactor.callLater(0.0, _produce)
  139. def unregisterProducer(self):
  140. if self._producer is None:
  141. return
  142. self._producer = None
  143. def requestDone(self, _self):
  144. self.result["done"] = True
  145. def getPeer(self):
  146. # We give an address so that getClientIP returns a non null entry,
  147. # causing us to record the MAU
  148. return address.IPv4Address("TCP", self._ip, 3423)
  149. def getHost(self):
  150. # this is called by Request.__init__ to configure Request.host.
  151. return address.IPv4Address("TCP", "127.0.0.1", 8888)
  152. def isSecure(self):
  153. return False
  154. @property
  155. def transport(self):
  156. return self
  157. def await_result(self, timeout_ms: int = 1000) -> None:
  158. """
  159. Wait until the request is finished.
  160. """
  161. end_time = self._reactor.seconds() + timeout_ms / 1000.0
  162. self._reactor.run()
  163. while not self.is_finished():
  164. # If there's a producer, tell it to resume producing so we get content
  165. if self._producer:
  166. self._producer.resumeProducing()
  167. if self._reactor.seconds() > end_time:
  168. raise TimedOutException("Timed out waiting for request to finish.")
  169. self._reactor.advance(0.1)
  170. def extract_cookies(self, cookies: MutableMapping[str, str]) -> None:
  171. """Process the contents of any Set-Cookie headers in the response
  172. Any cookines found are added to the given dict
  173. """
  174. headers = self.headers.getRawHeaders("Set-Cookie")
  175. if not headers:
  176. return
  177. for h in headers:
  178. parts = h.split(";")
  179. k, v = parts[0].split("=", maxsplit=1)
  180. cookies[k] = v
  181. class FakeSite:
  182. """
  183. A fake Twisted Web Site, with mocks of the extra things that
  184. Synapse adds.
  185. """
  186. server_version_string = b"1"
  187. site_tag = "test"
  188. access_logger = logging.getLogger("synapse.access.http.fake")
  189. def __init__(self, resource: IResource, reactor: IReactorTime):
  190. """
  191. Args:
  192. resource: the resource to be used for rendering all requests
  193. """
  194. self._resource = resource
  195. self.reactor = reactor
  196. def getResourceFor(self, request):
  197. return self._resource
  198. def make_request(
  199. reactor,
  200. site: Union[Site, FakeSite],
  201. method: Union[bytes, str],
  202. path: Union[bytes, str],
  203. content: Union[bytes, str, JsonDict] = b"",
  204. access_token: Optional[str] = None,
  205. request: Type[Request] = SynapseRequest,
  206. shorthand: bool = True,
  207. federation_auth_origin: Optional[bytes] = None,
  208. content_is_form: bool = False,
  209. await_result: bool = True,
  210. custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
  211. client_ip: str = "127.0.0.1",
  212. ) -> FakeChannel:
  213. """
  214. Make a web request using the given method, path and content, and render it
  215. Returns the fake Channel object which records the response to the request.
  216. Args:
  217. reactor:
  218. site: The twisted Site to use to render the request
  219. method: The HTTP request method ("verb").
  220. path: The HTTP path, suitably URL encoded (e.g. escaped UTF-8 & spaces and such).
  221. content: The body of the request. JSON-encoded, if a str of bytes.
  222. access_token: The access token to add as authorization for the request.
  223. request: The request class to create.
  224. shorthand: Whether to try and be helpful and prefix the given URL
  225. with the usual REST API path, if it doesn't contain it.
  226. federation_auth_origin: if set to not-None, we will add a fake
  227. Authorization header pretenting to be the given server name.
  228. content_is_form: Whether the content is URL encoded form data. Adds the
  229. 'Content-Type': 'application/x-www-form-urlencoded' header.
  230. await_result: whether to wait for the request to complete rendering. If true,
  231. will pump the reactor until the the renderer tells the channel the request
  232. is finished.
  233. custom_headers: (name, value) pairs to add as request headers
  234. client_ip: The IP to use as the requesting IP. Useful for testing
  235. ratelimiting.
  236. Returns:
  237. channel
  238. """
  239. if not isinstance(method, bytes):
  240. method = method.encode("ascii")
  241. if not isinstance(path, bytes):
  242. path = path.encode("ascii")
  243. # Decorate it to be the full path, if we're using shorthand
  244. if (
  245. shorthand
  246. and not path.startswith(b"/_matrix")
  247. and not path.startswith(b"/_synapse")
  248. ):
  249. if path.startswith(b"/"):
  250. path = path[1:]
  251. path = b"/_matrix/client/r0/" + path
  252. if not path.startswith(b"/"):
  253. path = b"/" + path
  254. if isinstance(content, dict):
  255. content = json.dumps(content).encode("utf8")
  256. if isinstance(content, str):
  257. content = content.encode("utf8")
  258. channel = FakeChannel(site, reactor, ip=client_ip)
  259. req = request(channel, site)
  260. req.content = BytesIO(content)
  261. # Twisted expects to be at the end of the content when parsing the request.
  262. req.content.seek(0, SEEK_END)
  263. if access_token:
  264. req.requestHeaders.addRawHeader(
  265. b"Authorization", b"Bearer " + access_token.encode("ascii")
  266. )
  267. if federation_auth_origin is not None:
  268. req.requestHeaders.addRawHeader(
  269. b"Authorization",
  270. b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin,),
  271. )
  272. if content:
  273. if content_is_form:
  274. req.requestHeaders.addRawHeader(
  275. b"Content-Type", b"application/x-www-form-urlencoded"
  276. )
  277. else:
  278. # Assume the body is JSON
  279. req.requestHeaders.addRawHeader(b"Content-Type", b"application/json")
  280. if custom_headers:
  281. for k, v in custom_headers:
  282. req.requestHeaders.addRawHeader(k, v)
  283. req.parseCookies()
  284. req.requestReceived(method, path, b"1.1")
  285. if await_result:
  286. channel.await_result()
  287. return channel
  288. @implementer(IReactorPluggableNameResolver)
  289. class ThreadedMemoryReactorClock(MemoryReactorClock):
  290. """
  291. A MemoryReactorClock that supports callFromThread.
  292. """
  293. def __init__(self):
  294. self.threadpool = ThreadPool(self)
  295. self._tcp_callbacks: Dict[Tuple[str, int], Callable] = {}
  296. self._udp = []
  297. self.lookups: Dict[str, str] = {}
  298. self._thread_callbacks: Deque[Callable[[], None]] = deque()
  299. lookups = self.lookups
  300. @implementer(IResolverSimple)
  301. class FakeResolver:
  302. def getHostByName(self, name, timeout=None):
  303. if name not in lookups:
  304. return fail(DNSLookupError("OH NO: unknown %s" % (name,)))
  305. return succeed(lookups[name])
  306. self.nameResolver = SimpleResolverComplexifier(FakeResolver())
  307. super().__init__()
  308. def installNameResolver(self, resolver: IHostnameResolver) -> IHostnameResolver:
  309. raise NotImplementedError()
  310. def listenUDP(self, port, protocol, interface="", maxPacketSize=8196):
  311. p = udp.Port(port, protocol, interface, maxPacketSize, self)
  312. p.startListening()
  313. self._udp.append(p)
  314. return p
  315. def callFromThread(self, callback, *args, **kwargs):
  316. """
  317. Make the callback fire in the next reactor iteration.
  318. """
  319. cb = lambda: callback(*args, **kwargs)
  320. # it's not safe to call callLater() here, so we append the callback to a
  321. # separate queue.
  322. self._thread_callbacks.append(cb)
  323. def getThreadPool(self):
  324. return self.threadpool
  325. def add_tcp_client_callback(self, host: str, port: int, callback: Callable):
  326. """Add a callback that will be invoked when we receive a connection
  327. attempt to the given IP/port using `connectTCP`.
  328. Note that the callback gets run before we return the connection to the
  329. client, which means callbacks cannot block while waiting for writes.
  330. """
  331. self._tcp_callbacks[(host, port)] = callback
  332. def connectTCP(self, host: str, port: int, factory, timeout=30, bindAddress=None):
  333. """Fake L{IReactorTCP.connectTCP}."""
  334. conn = super().connectTCP(
  335. host, port, factory, timeout=timeout, bindAddress=None
  336. )
  337. callback = self._tcp_callbacks.get((host, port))
  338. if callback:
  339. callback()
  340. return conn
  341. def advance(self, amount):
  342. # first advance our reactor's time, and run any "callLater" callbacks that
  343. # makes ready
  344. super().advance(amount)
  345. # now run any "callFromThread" callbacks
  346. while True:
  347. try:
  348. callback = self._thread_callbacks.popleft()
  349. except IndexError:
  350. break
  351. callback()
  352. # check for more "callLater" callbacks added by the thread callback
  353. # This isn't required in a regular reactor, but it ends up meaning that
  354. # our database queries can complete in a single call to `advance` [1] which
  355. # simplifies tests.
  356. #
  357. # [1]: we replace the threadpool backing the db connection pool with a
  358. # mock ThreadPool which doesn't really use threads; but we still use
  359. # reactor.callFromThread to feed results back from the db functions to the
  360. # main thread.
  361. super().advance(0)
  362. class ThreadPool:
  363. """
  364. Threadless thread pool.
  365. """
  366. def __init__(self, reactor):
  367. self._reactor = reactor
  368. def start(self):
  369. pass
  370. def stop(self):
  371. pass
  372. def callInThreadWithCallback(self, onResult, function, *args, **kwargs):
  373. def _(res):
  374. if isinstance(res, Failure):
  375. onResult(False, res)
  376. else:
  377. onResult(True, res)
  378. d = Deferred()
  379. d.addCallback(lambda x: function(*args, **kwargs))
  380. d.addBoth(_)
  381. self._reactor.callLater(0, d.callback, True)
  382. return d
  383. def _make_test_homeserver_synchronous(server: HomeServer) -> None:
  384. """
  385. Make the given test homeserver's database interactions synchronous.
  386. """
  387. clock = server.get_clock()
  388. for database in server.get_datastores().databases:
  389. pool = database._db_pool
  390. def runWithConnection(func, *args, **kwargs):
  391. return threads.deferToThreadPool(
  392. pool._reactor,
  393. pool.threadpool,
  394. pool._runWithConnection,
  395. func,
  396. *args,
  397. **kwargs,
  398. )
  399. def runInteraction(interaction, *args, **kwargs):
  400. return threads.deferToThreadPool(
  401. pool._reactor,
  402. pool.threadpool,
  403. pool._runInteraction,
  404. interaction,
  405. *args,
  406. **kwargs,
  407. )
  408. pool.runWithConnection = runWithConnection
  409. pool.runInteraction = runInteraction
  410. # Replace the thread pool with a threadless 'thread' pool
  411. pool.threadpool = ThreadPool(clock._reactor)
  412. pool.running = True
  413. # We've just changed the Databases to run DB transactions on the same
  414. # thread, so we need to disable the dedicated thread behaviour.
  415. server.get_datastores().main.USE_DEDICATED_DB_THREADS_FOR_EVENT_FETCHING = False
  416. def get_clock() -> Tuple[ThreadedMemoryReactorClock, Clock]:
  417. clock = ThreadedMemoryReactorClock()
  418. hs_clock = Clock(clock)
  419. return clock, hs_clock
  420. @implementer(ITransport)
  421. @attr.s(cmp=False)
  422. class FakeTransport:
  423. """
  424. A twisted.internet.interfaces.ITransport implementation which sends all its data
  425. straight into an IProtocol object: it exists to connect two IProtocols together.
  426. To use it, instantiate it with the receiving IProtocol, and then pass it to the
  427. sending IProtocol's makeConnection method:
  428. server = HTTPChannel()
  429. client.makeConnection(FakeTransport(server, self.reactor))
  430. If you want bidirectional communication, you'll need two instances.
  431. """
  432. other = attr.ib()
  433. """The Protocol object which will receive any data written to this transport.
  434. :type: twisted.internet.interfaces.IProtocol
  435. """
  436. _reactor = attr.ib()
  437. """Test reactor
  438. :type: twisted.internet.interfaces.IReactorTime
  439. """
  440. _protocol = attr.ib(default=None)
  441. """The Protocol which is producing data for this transport. Optional, but if set
  442. will get called back for connectionLost() notifications etc.
  443. """
  444. _peer_address: Optional[IAddress] = attr.ib(default=None)
  445. """The value to be returend by getPeer"""
  446. disconnecting = False
  447. disconnected = False
  448. connected = True
  449. buffer = attr.ib(default=b"")
  450. producer = attr.ib(default=None)
  451. autoflush = attr.ib(default=True)
  452. def getPeer(self):
  453. return self._peer_address
  454. def getHost(self):
  455. return None
  456. def loseConnection(self, reason=None):
  457. if not self.disconnecting:
  458. logger.info("FakeTransport: loseConnection(%s)", reason)
  459. self.disconnecting = True
  460. if self._protocol:
  461. self._protocol.connectionLost(reason)
  462. # if we still have data to write, delay until that is done
  463. if self.buffer:
  464. logger.info(
  465. "FakeTransport: Delaying disconnect until buffer is flushed"
  466. )
  467. else:
  468. self.connected = False
  469. self.disconnected = True
  470. def abortConnection(self):
  471. logger.info("FakeTransport: abortConnection()")
  472. if not self.disconnecting:
  473. self.disconnecting = True
  474. if self._protocol:
  475. self._protocol.connectionLost(None)
  476. self.disconnected = True
  477. def pauseProducing(self):
  478. if not self.producer:
  479. return
  480. self.producer.pauseProducing()
  481. def resumeProducing(self):
  482. if not self.producer:
  483. return
  484. self.producer.resumeProducing()
  485. def unregisterProducer(self):
  486. if not self.producer:
  487. return
  488. self.producer = None
  489. def registerProducer(self, producer, streaming):
  490. self.producer = producer
  491. self.producerStreaming = streaming
  492. def _produce():
  493. if not self.producer:
  494. # we've been unregistered
  495. return
  496. # some implementations of IProducer (for example, FileSender)
  497. # don't return a deferred.
  498. d = maybeDeferred(self.producer.resumeProducing)
  499. d.addCallback(lambda x: self._reactor.callLater(0.1, _produce))
  500. if not streaming:
  501. self._reactor.callLater(0.0, _produce)
  502. def write(self, byt):
  503. if self.disconnecting:
  504. raise Exception("Writing to disconnecting FakeTransport")
  505. self.buffer = self.buffer + byt
  506. # always actually do the write asynchronously. Some protocols (notably the
  507. # TLSMemoryBIOProtocol) get very confused if a read comes back while they are
  508. # still doing a write. Doing a callLater here breaks the cycle.
  509. if self.autoflush:
  510. self._reactor.callLater(0.0, self.flush)
  511. def writeSequence(self, seq):
  512. for x in seq:
  513. self.write(x)
  514. def flush(self, maxbytes=None):
  515. if not self.buffer:
  516. # nothing to do. Don't write empty buffers: it upsets the
  517. # TLSMemoryBIOProtocol
  518. return
  519. if self.disconnected:
  520. return
  521. if maxbytes is not None:
  522. to_write = self.buffer[:maxbytes]
  523. else:
  524. to_write = self.buffer
  525. logger.info("%s->%s: %s", self._protocol, self.other, to_write)
  526. try:
  527. self.other.dataReceived(to_write)
  528. except Exception as e:
  529. logger.exception("Exception writing to protocol: %s", e)
  530. return
  531. self.buffer = self.buffer[len(to_write) :]
  532. if self.buffer and self.autoflush:
  533. self._reactor.callLater(0.0, self.flush)
  534. if not self.buffer and self.disconnecting:
  535. logger.info("FakeTransport: Buffer now empty, completing disconnect")
  536. self.disconnected = True
  537. def connect_client(
  538. reactor: ThreadedMemoryReactorClock, client_id: int
  539. ) -> Tuple[IProtocol, AccumulatingProtocol]:
  540. """
  541. Connect a client to a fake TCP transport.
  542. Args:
  543. reactor
  544. factory: The connecting factory to build.
  545. """
  546. factory = reactor.tcpClients.pop(client_id)[2]
  547. client = factory.buildProtocol(None)
  548. server = AccumulatingProtocol()
  549. server.makeConnection(FakeTransport(client, reactor))
  550. client.makeConnection(FakeTransport(server, reactor))
  551. return client, server
  552. class TestHomeServer(HomeServer):
  553. DATASTORE_CLASS = DataStore
  554. def setup_test_homeserver(
  555. cleanup_func,
  556. name="test",
  557. config=None,
  558. reactor=None,
  559. homeserver_to_use: Type[HomeServer] = TestHomeServer,
  560. **kwargs,
  561. ):
  562. """
  563. Setup a homeserver suitable for running tests against. Keyword arguments
  564. are passed to the Homeserver constructor.
  565. If no datastore is supplied, one is created and given to the homeserver.
  566. Args:
  567. cleanup_func : The function used to register a cleanup routine for
  568. after the test.
  569. Calling this method directly is deprecated: you should instead derive from
  570. HomeserverTestCase.
  571. """
  572. if reactor is None:
  573. from twisted.internet import reactor
  574. if config is None:
  575. config = default_config(name, parse=True)
  576. config.ldap_enabled = False
  577. if "clock" not in kwargs:
  578. kwargs["clock"] = MockClock()
  579. if USE_POSTGRES_FOR_TESTS:
  580. test_db = "synapse_test_%s" % uuid.uuid4().hex
  581. database_config = {
  582. "name": "psycopg2",
  583. "args": {
  584. "database": test_db,
  585. "host": POSTGRES_HOST,
  586. "password": POSTGRES_PASSWORD,
  587. "user": POSTGRES_USER,
  588. "cp_min": 1,
  589. "cp_max": 5,
  590. },
  591. }
  592. else:
  593. if SQLITE_PERSIST_DB:
  594. # The current working directory is in _trial_temp, so this gets created within that directory.
  595. test_db_location = os.path.abspath("test.db")
  596. logger.debug("Will persist db to %s", test_db_location)
  597. # Ensure each test gets a clean database.
  598. try:
  599. os.remove(test_db_location)
  600. except FileNotFoundError:
  601. pass
  602. else:
  603. logger.debug("Removed existing DB at %s", test_db_location)
  604. else:
  605. test_db_location = ":memory:"
  606. database_config = {
  607. "name": "sqlite3",
  608. "args": {"database": test_db_location, "cp_min": 1, "cp_max": 1},
  609. }
  610. if "db_txn_limit" in kwargs:
  611. database_config["txn_limit"] = kwargs["db_txn_limit"]
  612. database = DatabaseConnectionConfig("master", database_config)
  613. config.database.databases = [database]
  614. db_engine = create_engine(database.config)
  615. # Create the database before we actually try and connect to it, based off
  616. # the template database we generate in setupdb()
  617. if isinstance(db_engine, PostgresEngine):
  618. db_conn = db_engine.module.connect(
  619. database=POSTGRES_BASE_DB,
  620. user=POSTGRES_USER,
  621. host=POSTGRES_HOST,
  622. password=POSTGRES_PASSWORD,
  623. )
  624. db_conn.autocommit = True
  625. cur = db_conn.cursor()
  626. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  627. cur.execute(
  628. "CREATE DATABASE %s WITH TEMPLATE %s;" % (test_db, POSTGRES_BASE_DB)
  629. )
  630. cur.close()
  631. db_conn.close()
  632. hs = homeserver_to_use(
  633. name,
  634. config=config,
  635. version_string="Synapse/tests",
  636. reactor=reactor,
  637. )
  638. # Install @cache_in_self attributes
  639. for key, val in kwargs.items():
  640. setattr(hs, "_" + key, val)
  641. # Mock TLS
  642. hs.tls_server_context_factory = Mock()
  643. hs.tls_client_options_factory = Mock()
  644. hs.setup()
  645. if homeserver_to_use == TestHomeServer:
  646. hs.setup_background_tasks()
  647. if isinstance(db_engine, PostgresEngine):
  648. database = hs.get_datastores().databases[0]
  649. # We need to do cleanup on PostgreSQL
  650. def cleanup():
  651. import psycopg2
  652. # Close all the db pools
  653. database._db_pool.close()
  654. dropped = False
  655. # Drop the test database
  656. db_conn = db_engine.module.connect(
  657. database=POSTGRES_BASE_DB,
  658. user=POSTGRES_USER,
  659. host=POSTGRES_HOST,
  660. password=POSTGRES_PASSWORD,
  661. )
  662. db_conn.autocommit = True
  663. cur = db_conn.cursor()
  664. # Try a few times to drop the DB. Some things may hold on to the
  665. # database for a few more seconds due to flakiness, preventing
  666. # us from dropping it when the test is over. If we can't drop
  667. # it, warn and move on.
  668. for _ in range(5):
  669. try:
  670. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  671. db_conn.commit()
  672. dropped = True
  673. except psycopg2.OperationalError as e:
  674. warnings.warn(
  675. "Couldn't drop old db: " + str(e), category=UserWarning
  676. )
  677. time.sleep(0.5)
  678. cur.close()
  679. db_conn.close()
  680. if not dropped:
  681. warnings.warn("Failed to drop old DB.", category=UserWarning)
  682. if not LEAVE_DB:
  683. # Register the cleanup hook
  684. cleanup_func(cleanup)
  685. # bcrypt is far too slow to be doing in unit tests
  686. # Need to let the HS build an auth handler and then mess with it
  687. # because AuthHandler's constructor requires the HS, so we can't make one
  688. # beforehand and pass it in to the HS's constructor (chicken / egg)
  689. async def hash(p):
  690. return hashlib.md5(p.encode("utf8")).hexdigest()
  691. hs.get_auth_handler().hash = hash
  692. async def validate_hash(p, h):
  693. return hashlib.md5(p.encode("utf8")).hexdigest() == h
  694. hs.get_auth_handler().validate_hash = validate_hash
  695. # Make the threadpool and database transactions synchronous for testing.
  696. _make_test_homeserver_synchronous(hs)
  697. return hs