server.py 26 KB

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