server.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # This file provides some classes for setting up (partially-populated)
  16. # homeservers; either as a full homeserver as a real application, or a small
  17. # partial one for unit test mocking.
  18. # Imports required for the default HomeServer() implementation
  19. import abc
  20. import logging
  21. from twisted.enterprise import adbapi
  22. from twisted.mail.smtp import sendmail
  23. from twisted.web.client import BrowserLikePolicyForHTTPS
  24. from synapse.api.auth import Auth
  25. from synapse.api.filtering import Filtering
  26. from synapse.api.ratelimiting import Ratelimiter
  27. from synapse.appservice.api import ApplicationServiceApi
  28. from synapse.appservice.scheduler import ApplicationServiceScheduler
  29. from synapse.crypto.keyring import Keyring
  30. from synapse.events.builder import EventBuilderFactory
  31. from synapse.events.spamcheck import SpamChecker
  32. from synapse.federation.federation_client import FederationClient
  33. from synapse.federation.federation_server import (
  34. FederationHandlerRegistry,
  35. FederationServer,
  36. ReplicationFederationHandlerRegistry,
  37. )
  38. from synapse.federation.send_queue import FederationRemoteSendQueue
  39. from synapse.federation.transaction_queue import TransactionQueue
  40. from synapse.federation.transport.client import TransportLayerClient
  41. from synapse.groups.attestations import GroupAttestationSigning, GroupAttestionRenewer
  42. from synapse.groups.groups_server import GroupsServerHandler
  43. from synapse.handlers import Handlers
  44. from synapse.handlers.acme import AcmeHandler
  45. from synapse.handlers.appservice import ApplicationServicesHandler
  46. from synapse.handlers.auth import AuthHandler, MacaroonGenerator
  47. from synapse.handlers.deactivate_account import DeactivateAccountHandler
  48. from synapse.handlers.device import DeviceHandler
  49. from synapse.handlers.devicemessage import DeviceMessageHandler
  50. from synapse.handlers.e2e_keys import E2eKeysHandler
  51. from synapse.handlers.e2e_room_keys import E2eRoomKeysHandler
  52. from synapse.handlers.events import EventHandler, EventStreamHandler
  53. from synapse.handlers.groups_local import GroupsLocalHandler
  54. from synapse.handlers.initial_sync import InitialSyncHandler
  55. from synapse.handlers.message import EventCreationHandler, MessageHandler
  56. from synapse.handlers.pagination import PaginationHandler
  57. from synapse.handlers.presence import PresenceHandler
  58. from synapse.handlers.profile import BaseProfileHandler, MasterProfileHandler
  59. from synapse.handlers.read_marker import ReadMarkerHandler
  60. from synapse.handlers.receipts import ReceiptsHandler
  61. from synapse.handlers.room import RoomContextHandler, RoomCreationHandler
  62. from synapse.handlers.room_list import RoomListHandler
  63. from synapse.handlers.room_member import RoomMemberMasterHandler
  64. from synapse.handlers.room_member_worker import RoomMemberWorkerHandler
  65. from synapse.handlers.set_password import SetPasswordHandler
  66. from synapse.handlers.sync import SyncHandler
  67. from synapse.handlers.typing import TypingHandler
  68. from synapse.handlers.user_directory import UserDirectoryHandler
  69. from synapse.http.client import InsecureInterceptableContextFactory, SimpleHttpClient
  70. from synapse.http.matrixfederationclient import MatrixFederationHttpClient
  71. from synapse.notifier import Notifier
  72. from synapse.push.action_generator import ActionGenerator
  73. from synapse.push.pusherpool import PusherPool
  74. from synapse.rest.media.v1.media_repository import (
  75. MediaRepository,
  76. MediaRepositoryResource,
  77. )
  78. from synapse.secrets import Secrets
  79. from synapse.server_notices.server_notices_manager import ServerNoticesManager
  80. from synapse.server_notices.server_notices_sender import ServerNoticesSender
  81. from synapse.server_notices.worker_server_notices_sender import WorkerServerNoticesSender
  82. from synapse.state import StateHandler, StateResolutionHandler
  83. from synapse.streams.events import EventSources
  84. from synapse.util import Clock
  85. from synapse.util.distributor import Distributor
  86. logger = logging.getLogger(__name__)
  87. class HomeServer(object):
  88. """A basic homeserver object without lazy component builders.
  89. This will need all of the components it requires to either be passed as
  90. constructor arguments, or the relevant methods overriding to create them.
  91. Typically this would only be used for unit tests.
  92. For every dependency in the DEPENDENCIES list below, this class creates one
  93. method,
  94. def get_DEPENDENCY(self)
  95. which returns the value of that dependency. If no value has yet been set
  96. nor was provided to the constructor, it will attempt to call a lazy builder
  97. method called
  98. def build_DEPENDENCY(self)
  99. which must be implemented by the subclass. This code may call any of the
  100. required "get" methods on the instance to obtain the sub-dependencies that
  101. one requires.
  102. Attributes:
  103. config (synapse.config.homeserver.HomeserverConfig):
  104. """
  105. __metaclass__ = abc.ABCMeta
  106. DEPENDENCIES = [
  107. 'http_client',
  108. 'db_pool',
  109. 'federation_client',
  110. 'federation_server',
  111. 'handlers',
  112. 'auth',
  113. 'room_creation_handler',
  114. 'state_handler',
  115. 'state_resolution_handler',
  116. 'presence_handler',
  117. 'sync_handler',
  118. 'typing_handler',
  119. 'room_list_handler',
  120. 'acme_handler',
  121. 'auth_handler',
  122. 'device_handler',
  123. 'e2e_keys_handler',
  124. 'e2e_room_keys_handler',
  125. 'event_handler',
  126. 'event_stream_handler',
  127. 'initial_sync_handler',
  128. 'application_service_api',
  129. 'application_service_scheduler',
  130. 'application_service_handler',
  131. 'device_message_handler',
  132. 'profile_handler',
  133. 'event_creation_handler',
  134. 'deactivate_account_handler',
  135. 'set_password_handler',
  136. 'notifier',
  137. 'event_sources',
  138. 'keyring',
  139. 'pusherpool',
  140. 'event_builder_factory',
  141. 'filtering',
  142. 'http_client_context_factory',
  143. 'simple_http_client',
  144. 'media_repository',
  145. 'media_repository_resource',
  146. 'federation_transport_client',
  147. 'federation_sender',
  148. 'receipts_handler',
  149. 'macaroon_generator',
  150. 'tcp_replication',
  151. 'read_marker_handler',
  152. 'action_generator',
  153. 'user_directory_handler',
  154. 'groups_local_handler',
  155. 'groups_server_handler',
  156. 'groups_attestation_signing',
  157. 'groups_attestation_renewer',
  158. 'secrets',
  159. 'spam_checker',
  160. 'room_member_handler',
  161. 'federation_registry',
  162. 'server_notices_manager',
  163. 'server_notices_sender',
  164. 'message_handler',
  165. 'pagination_handler',
  166. 'room_context_handler',
  167. 'sendmail',
  168. ]
  169. # This is overridden in derived application classes
  170. # (such as synapse.app.homeserver.SynapseHomeServer) and gives the class to be
  171. # instantiated during setup() for future return by get_datastore()
  172. DATASTORE_CLASS = abc.abstractproperty()
  173. def __init__(self, hostname, reactor=None, **kwargs):
  174. """
  175. Args:
  176. hostname : The hostname for the server.
  177. """
  178. if not reactor:
  179. from twisted.internet import reactor
  180. self._reactor = reactor
  181. self.hostname = hostname
  182. self._building = {}
  183. self.clock = Clock(reactor)
  184. self.distributor = Distributor()
  185. self.ratelimiter = Ratelimiter()
  186. self.datastore = None
  187. # Other kwargs are explicit dependencies
  188. for depname in kwargs:
  189. setattr(self, depname, kwargs[depname])
  190. def setup(self):
  191. logger.info("Setting up.")
  192. with self.get_db_conn() as conn:
  193. self.datastore = self.DATASTORE_CLASS(conn, self)
  194. conn.commit()
  195. logger.info("Finished setting up.")
  196. def get_reactor(self):
  197. """
  198. Fetch the Twisted reactor in use by this HomeServer.
  199. """
  200. return self._reactor
  201. def get_ip_from_request(self, request):
  202. # X-Forwarded-For is handled by our custom request type.
  203. return request.getClientIP()
  204. def is_mine(self, domain_specific_string):
  205. return domain_specific_string.domain == self.hostname
  206. def is_mine_id(self, string):
  207. return string.split(":", 1)[1] == self.hostname
  208. def get_clock(self):
  209. return self.clock
  210. def get_datastore(self):
  211. return self.datastore
  212. def get_config(self):
  213. return self.config
  214. def get_distributor(self):
  215. return self.distributor
  216. def get_ratelimiter(self):
  217. return self.ratelimiter
  218. def build_federation_client(self):
  219. return FederationClient(self)
  220. def build_federation_server(self):
  221. return FederationServer(self)
  222. def build_handlers(self):
  223. return Handlers(self)
  224. def build_notifier(self):
  225. return Notifier(self)
  226. def build_auth(self):
  227. return Auth(self)
  228. def build_http_client_context_factory(self):
  229. return (
  230. InsecureInterceptableContextFactory()
  231. if self.config.use_insecure_ssl_client_just_for_testing_do_not_use
  232. else BrowserLikePolicyForHTTPS()
  233. )
  234. def build_simple_http_client(self):
  235. return SimpleHttpClient(self)
  236. def build_room_creation_handler(self):
  237. return RoomCreationHandler(self)
  238. def build_sendmail(self):
  239. return sendmail
  240. def build_state_handler(self):
  241. return StateHandler(self)
  242. def build_state_resolution_handler(self):
  243. return StateResolutionHandler(self)
  244. def build_presence_handler(self):
  245. return PresenceHandler(self)
  246. def build_typing_handler(self):
  247. return TypingHandler(self)
  248. def build_sync_handler(self):
  249. return SyncHandler(self)
  250. def build_room_list_handler(self):
  251. return RoomListHandler(self)
  252. def build_auth_handler(self):
  253. return AuthHandler(self)
  254. def build_macaroon_generator(self):
  255. return MacaroonGenerator(self)
  256. def build_device_handler(self):
  257. return DeviceHandler(self)
  258. def build_device_message_handler(self):
  259. return DeviceMessageHandler(self)
  260. def build_e2e_keys_handler(self):
  261. return E2eKeysHandler(self)
  262. def build_e2e_room_keys_handler(self):
  263. return E2eRoomKeysHandler(self)
  264. def build_acme_handler(self):
  265. return AcmeHandler(self)
  266. def build_application_service_api(self):
  267. return ApplicationServiceApi(self)
  268. def build_application_service_scheduler(self):
  269. return ApplicationServiceScheduler(self)
  270. def build_application_service_handler(self):
  271. return ApplicationServicesHandler(self)
  272. def build_event_handler(self):
  273. return EventHandler(self)
  274. def build_event_stream_handler(self):
  275. return EventStreamHandler(self)
  276. def build_initial_sync_handler(self):
  277. return InitialSyncHandler(self)
  278. def build_profile_handler(self):
  279. if self.config.worker_app:
  280. return BaseProfileHandler(self)
  281. else:
  282. return MasterProfileHandler(self)
  283. def build_event_creation_handler(self):
  284. return EventCreationHandler(self)
  285. def build_deactivate_account_handler(self):
  286. return DeactivateAccountHandler(self)
  287. def build_set_password_handler(self):
  288. return SetPasswordHandler(self)
  289. def build_event_sources(self):
  290. return EventSources(self)
  291. def build_keyring(self):
  292. return Keyring(self)
  293. def build_event_builder_factory(self):
  294. return EventBuilderFactory(
  295. clock=self.get_clock(),
  296. hostname=self.hostname,
  297. )
  298. def build_filtering(self):
  299. return Filtering(self)
  300. def build_pusherpool(self):
  301. return PusherPool(self)
  302. def build_http_client(self):
  303. return MatrixFederationHttpClient(self)
  304. def build_db_pool(self):
  305. name = self.db_config["name"]
  306. return adbapi.ConnectionPool(
  307. name,
  308. cp_reactor=self.get_reactor(),
  309. **self.db_config.get("args", {})
  310. )
  311. def get_db_conn(self, run_new_connection=True):
  312. """Makes a new connection to the database, skipping the db pool
  313. Returns:
  314. Connection: a connection object implementing the PEP-249 spec
  315. """
  316. # Any param beginning with cp_ is a parameter for adbapi, and should
  317. # not be passed to the database engine.
  318. db_params = {
  319. k: v for k, v in self.db_config.get("args", {}).items()
  320. if not k.startswith("cp_")
  321. }
  322. db_conn = self.database_engine.module.connect(**db_params)
  323. if run_new_connection:
  324. self.database_engine.on_new_connection(db_conn)
  325. return db_conn
  326. def build_media_repository_resource(self):
  327. # build the media repo resource. This indirects through the HomeServer
  328. # to ensure that we only have a single instance of
  329. return MediaRepositoryResource(self)
  330. def build_media_repository(self):
  331. return MediaRepository(self)
  332. def build_federation_transport_client(self):
  333. return TransportLayerClient(self)
  334. def build_federation_sender(self):
  335. if self.should_send_federation():
  336. return TransactionQueue(self)
  337. elif not self.config.worker_app:
  338. return FederationRemoteSendQueue(self)
  339. else:
  340. raise Exception("Workers cannot send federation traffic")
  341. def build_receipts_handler(self):
  342. return ReceiptsHandler(self)
  343. def build_read_marker_handler(self):
  344. return ReadMarkerHandler(self)
  345. def build_tcp_replication(self):
  346. raise NotImplementedError()
  347. def build_action_generator(self):
  348. return ActionGenerator(self)
  349. def build_user_directory_handler(self):
  350. return UserDirectoryHandler(self)
  351. def build_groups_local_handler(self):
  352. return GroupsLocalHandler(self)
  353. def build_groups_server_handler(self):
  354. return GroupsServerHandler(self)
  355. def build_groups_attestation_signing(self):
  356. return GroupAttestationSigning(self)
  357. def build_groups_attestation_renewer(self):
  358. return GroupAttestionRenewer(self)
  359. def build_secrets(self):
  360. return Secrets()
  361. def build_spam_checker(self):
  362. return SpamChecker(self)
  363. def build_room_member_handler(self):
  364. if self.config.worker_app:
  365. return RoomMemberWorkerHandler(self)
  366. return RoomMemberMasterHandler(self)
  367. def build_federation_registry(self):
  368. if self.config.worker_app:
  369. return ReplicationFederationHandlerRegistry(self)
  370. else:
  371. return FederationHandlerRegistry()
  372. def build_server_notices_manager(self):
  373. if self.config.worker_app:
  374. raise Exception("Workers cannot send server notices")
  375. return ServerNoticesManager(self)
  376. def build_server_notices_sender(self):
  377. if self.config.worker_app:
  378. return WorkerServerNoticesSender(self)
  379. return ServerNoticesSender(self)
  380. def build_message_handler(self):
  381. return MessageHandler(self)
  382. def build_pagination_handler(self):
  383. return PaginationHandler(self)
  384. def build_room_context_handler(self):
  385. return RoomContextHandler(self)
  386. def remove_pusher(self, app_id, push_key, user_id):
  387. return self.get_pusherpool().remove_pusher(app_id, push_key, user_id)
  388. def should_send_federation(self):
  389. "Should this server be sending federation traffic directly?"
  390. return self.config.send_federation and (
  391. not self.config.worker_app
  392. or self.config.worker_app == "synapse.app.federation_sender"
  393. )
  394. def _make_dependency_method(depname):
  395. def _get(hs):
  396. try:
  397. return getattr(hs, depname)
  398. except AttributeError:
  399. pass
  400. try:
  401. builder = getattr(hs, "build_%s" % (depname))
  402. except AttributeError:
  403. builder = None
  404. if builder:
  405. # Prevent cyclic dependencies from deadlocking
  406. if depname in hs._building:
  407. raise ValueError("Cyclic dependency while building %s" % (
  408. depname,
  409. ))
  410. hs._building[depname] = 1
  411. dep = builder()
  412. setattr(hs, depname, dep)
  413. del hs._building[depname]
  414. return dep
  415. raise NotImplementedError(
  416. "%s has no %s nor a builder for it" % (
  417. type(hs).__name__, depname,
  418. )
  419. )
  420. setattr(HomeServer, "get_%s" % (depname), _get)
  421. # Build magic accessors for every dependency
  422. for depname in HomeServer.DEPENDENCIES:
  423. _make_dependency_method(depname)