server.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 logging
  20. from twisted.enterprise import adbapi
  21. from twisted.web.client import BrowserLikePolicyForHTTPS
  22. from synapse.api.auth import Auth
  23. from synapse.api.filtering import Filtering
  24. from synapse.api.ratelimiting import Ratelimiter
  25. from synapse.appservice.api import ApplicationServiceApi
  26. from synapse.appservice.scheduler import ApplicationServiceScheduler
  27. from synapse.crypto.keyring import Keyring
  28. from synapse.events.builder import EventBuilderFactory
  29. from synapse.events.spamcheck import SpamChecker
  30. from synapse.federation.federation_client import FederationClient
  31. from synapse.federation.federation_server import FederationServer
  32. from synapse.federation.send_queue import FederationRemoteSendQueue
  33. from synapse.federation.federation_server import FederationHandlerRegistry
  34. from synapse.federation.transport.client import TransportLayerClient
  35. from synapse.federation.transaction_queue import TransactionQueue
  36. from synapse.handlers import Handlers
  37. from synapse.handlers.appservice import ApplicationServicesHandler
  38. from synapse.handlers.auth import AuthHandler, MacaroonGeneartor
  39. from synapse.handlers.deactivate_account import DeactivateAccountHandler
  40. from synapse.handlers.devicemessage import DeviceMessageHandler
  41. from synapse.handlers.device import DeviceHandler
  42. from synapse.handlers.e2e_keys import E2eKeysHandler
  43. from synapse.handlers.presence import PresenceHandler
  44. from synapse.handlers.room_list import RoomListHandler
  45. from synapse.handlers.room_member import RoomMemberMasterHandler
  46. from synapse.handlers.room_member_worker import RoomMemberWorkerHandler
  47. from synapse.handlers.set_password import SetPasswordHandler
  48. from synapse.handlers.sync import SyncHandler
  49. from synapse.handlers.typing import TypingHandler
  50. from synapse.handlers.events import EventHandler, EventStreamHandler
  51. from synapse.handlers.initial_sync import InitialSyncHandler
  52. from synapse.handlers.receipts import ReceiptsHandler
  53. from synapse.handlers.read_marker import ReadMarkerHandler
  54. from synapse.handlers.user_directory import UserDirectoryHandler
  55. from synapse.handlers.groups_local import GroupsLocalHandler
  56. from synapse.handlers.profile import ProfileHandler
  57. from synapse.handlers.message import EventCreationHandler
  58. from synapse.groups.groups_server import GroupsServerHandler
  59. from synapse.groups.attestations import GroupAttestionRenewer, GroupAttestationSigning
  60. from synapse.http.client import SimpleHttpClient, InsecureInterceptableContextFactory
  61. from synapse.http.matrixfederationclient import MatrixFederationHttpClient
  62. from synapse.notifier import Notifier
  63. from synapse.push.action_generator import ActionGenerator
  64. from synapse.push.pusherpool import PusherPool
  65. from synapse.rest.media.v1.media_repository import (
  66. MediaRepository,
  67. MediaRepositoryResource,
  68. )
  69. from synapse.state import StateHandler, StateResolutionHandler
  70. from synapse.storage import DataStore
  71. from synapse.streams.events import EventSources
  72. from synapse.util import Clock
  73. from synapse.util.distributor import Distributor
  74. logger = logging.getLogger(__name__)
  75. class HomeServer(object):
  76. """A basic homeserver object without lazy component builders.
  77. This will need all of the components it requires to either be passed as
  78. constructor arguments, or the relevant methods overriding to create them.
  79. Typically this would only be used for unit tests.
  80. For every dependency in the DEPENDENCIES list below, this class creates one
  81. method,
  82. def get_DEPENDENCY(self)
  83. which returns the value of that dependency. If no value has yet been set
  84. nor was provided to the constructor, it will attempt to call a lazy builder
  85. method called
  86. def build_DEPENDENCY(self)
  87. which must be implemented by the subclass. This code may call any of the
  88. required "get" methods on the instance to obtain the sub-dependencies that
  89. one requires.
  90. """
  91. DEPENDENCIES = [
  92. 'http_client',
  93. 'db_pool',
  94. 'federation_client',
  95. 'federation_server',
  96. 'handlers',
  97. 'auth',
  98. 'state_handler',
  99. 'state_resolution_handler',
  100. 'presence_handler',
  101. 'sync_handler',
  102. 'typing_handler',
  103. 'room_list_handler',
  104. 'auth_handler',
  105. 'device_handler',
  106. 'e2e_keys_handler',
  107. 'event_handler',
  108. 'event_stream_handler',
  109. 'initial_sync_handler',
  110. 'application_service_api',
  111. 'application_service_scheduler',
  112. 'application_service_handler',
  113. 'device_message_handler',
  114. 'profile_handler',
  115. 'event_creation_handler',
  116. 'deactivate_account_handler',
  117. 'set_password_handler',
  118. 'notifier',
  119. 'event_sources',
  120. 'keyring',
  121. 'pusherpool',
  122. 'event_builder_factory',
  123. 'filtering',
  124. 'http_client_context_factory',
  125. 'simple_http_client',
  126. 'media_repository',
  127. 'media_repository_resource',
  128. 'federation_transport_client',
  129. 'federation_sender',
  130. 'receipts_handler',
  131. 'macaroon_generator',
  132. 'tcp_replication',
  133. 'read_marker_handler',
  134. 'action_generator',
  135. 'user_directory_handler',
  136. 'groups_local_handler',
  137. 'groups_server_handler',
  138. 'groups_attestation_signing',
  139. 'groups_attestation_renewer',
  140. 'spam_checker',
  141. 'room_member_handler',
  142. 'federation_registry',
  143. ]
  144. def __init__(self, hostname, **kwargs):
  145. """
  146. Args:
  147. hostname : The hostname for the server.
  148. """
  149. self.hostname = hostname
  150. self._building = {}
  151. self.clock = Clock()
  152. self.distributor = Distributor()
  153. self.ratelimiter = Ratelimiter()
  154. # Other kwargs are explicit dependencies
  155. for depname in kwargs:
  156. setattr(self, depname, kwargs[depname])
  157. def setup(self):
  158. logger.info("Setting up.")
  159. self.datastore = DataStore(self.get_db_conn(), self)
  160. logger.info("Finished setting up.")
  161. def get_ip_from_request(self, request):
  162. # X-Forwarded-For is handled by our custom request type.
  163. return request.getClientIP()
  164. def is_mine(self, domain_specific_string):
  165. return domain_specific_string.domain == self.hostname
  166. def is_mine_id(self, string):
  167. return string.split(":", 1)[1] == self.hostname
  168. def get_clock(self):
  169. return self.clock
  170. def get_datastore(self):
  171. return self.datastore
  172. def get_config(self):
  173. return self.config
  174. def get_distributor(self):
  175. return self.distributor
  176. def get_ratelimiter(self):
  177. return self.ratelimiter
  178. def build_federation_client(self):
  179. return FederationClient(self)
  180. def build_federation_server(self):
  181. return FederationServer(self)
  182. def build_handlers(self):
  183. return Handlers(self)
  184. def build_notifier(self):
  185. return Notifier(self)
  186. def build_auth(self):
  187. return Auth(self)
  188. def build_http_client_context_factory(self):
  189. return (
  190. InsecureInterceptableContextFactory()
  191. if self.config.use_insecure_ssl_client_just_for_testing_do_not_use
  192. else BrowserLikePolicyForHTTPS()
  193. )
  194. def build_simple_http_client(self):
  195. return SimpleHttpClient(self)
  196. def build_state_handler(self):
  197. return StateHandler(self)
  198. def build_state_resolution_handler(self):
  199. return StateResolutionHandler(self)
  200. def build_presence_handler(self):
  201. return PresenceHandler(self)
  202. def build_typing_handler(self):
  203. return TypingHandler(self)
  204. def build_sync_handler(self):
  205. return SyncHandler(self)
  206. def build_room_list_handler(self):
  207. return RoomListHandler(self)
  208. def build_auth_handler(self):
  209. return AuthHandler(self)
  210. def build_macaroon_generator(self):
  211. return MacaroonGeneartor(self)
  212. def build_device_handler(self):
  213. return DeviceHandler(self)
  214. def build_device_message_handler(self):
  215. return DeviceMessageHandler(self)
  216. def build_e2e_keys_handler(self):
  217. return E2eKeysHandler(self)
  218. def build_application_service_api(self):
  219. return ApplicationServiceApi(self)
  220. def build_application_service_scheduler(self):
  221. return ApplicationServiceScheduler(self)
  222. def build_application_service_handler(self):
  223. return ApplicationServicesHandler(self)
  224. def build_event_handler(self):
  225. return EventHandler(self)
  226. def build_event_stream_handler(self):
  227. return EventStreamHandler(self)
  228. def build_initial_sync_handler(self):
  229. return InitialSyncHandler(self)
  230. def build_profile_handler(self):
  231. return ProfileHandler(self)
  232. def build_event_creation_handler(self):
  233. return EventCreationHandler(self)
  234. def build_deactivate_account_handler(self):
  235. return DeactivateAccountHandler(self)
  236. def build_set_password_handler(self):
  237. return SetPasswordHandler(self)
  238. def build_event_sources(self):
  239. return EventSources(self)
  240. def build_keyring(self):
  241. return Keyring(self)
  242. def build_event_builder_factory(self):
  243. return EventBuilderFactory(
  244. clock=self.get_clock(),
  245. hostname=self.hostname,
  246. )
  247. def build_filtering(self):
  248. return Filtering(self)
  249. def build_pusherpool(self):
  250. return PusherPool(self)
  251. def build_http_client(self):
  252. return MatrixFederationHttpClient(self)
  253. def build_db_pool(self):
  254. name = self.db_config["name"]
  255. return adbapi.ConnectionPool(
  256. name,
  257. **self.db_config.get("args", {})
  258. )
  259. def get_db_conn(self, run_new_connection=True):
  260. """Makes a new connection to the database, skipping the db pool
  261. Returns:
  262. Connection: a connection object implementing the PEP-249 spec
  263. """
  264. # Any param beginning with cp_ is a parameter for adbapi, and should
  265. # not be passed to the database engine.
  266. db_params = {
  267. k: v for k, v in self.db_config.get("args", {}).items()
  268. if not k.startswith("cp_")
  269. }
  270. db_conn = self.database_engine.module.connect(**db_params)
  271. if run_new_connection:
  272. self.database_engine.on_new_connection(db_conn)
  273. return db_conn
  274. def build_media_repository_resource(self):
  275. # build the media repo resource. This indirects through the HomeServer
  276. # to ensure that we only have a single instance of
  277. return MediaRepositoryResource(self)
  278. def build_media_repository(self):
  279. return MediaRepository(self)
  280. def build_federation_transport_client(self):
  281. return TransportLayerClient(self)
  282. def build_federation_sender(self):
  283. if self.should_send_federation():
  284. return TransactionQueue(self)
  285. elif not self.config.worker_app:
  286. return FederationRemoteSendQueue(self)
  287. else:
  288. raise Exception("Workers cannot send federation traffic")
  289. def build_receipts_handler(self):
  290. return ReceiptsHandler(self)
  291. def build_read_marker_handler(self):
  292. return ReadMarkerHandler(self)
  293. def build_tcp_replication(self):
  294. raise NotImplementedError()
  295. def build_action_generator(self):
  296. return ActionGenerator(self)
  297. def build_user_directory_handler(self):
  298. return UserDirectoryHandler(self)
  299. def build_groups_local_handler(self):
  300. return GroupsLocalHandler(self)
  301. def build_groups_server_handler(self):
  302. return GroupsServerHandler(self)
  303. def build_groups_attestation_signing(self):
  304. return GroupAttestationSigning(self)
  305. def build_groups_attestation_renewer(self):
  306. return GroupAttestionRenewer(self)
  307. def build_spam_checker(self):
  308. return SpamChecker(self)
  309. def build_room_member_handler(self):
  310. if self.config.worker_app:
  311. return RoomMemberWorkerHandler(self)
  312. return RoomMemberMasterHandler(self)
  313. def build_federation_registry(self):
  314. return FederationHandlerRegistry()
  315. def remove_pusher(self, app_id, push_key, user_id):
  316. return self.get_pusherpool().remove_pusher(app_id, push_key, user_id)
  317. def should_send_federation(self):
  318. "Should this server be sending federation traffic directly?"
  319. return self.config.send_federation and (
  320. not self.config.worker_app
  321. or self.config.worker_app == "synapse.app.federation_sender"
  322. )
  323. def _make_dependency_method(depname):
  324. def _get(hs):
  325. try:
  326. return getattr(hs, depname)
  327. except AttributeError:
  328. pass
  329. try:
  330. builder = getattr(hs, "build_%s" % (depname))
  331. except AttributeError:
  332. builder = None
  333. if builder:
  334. # Prevent cyclic dependencies from deadlocking
  335. if depname in hs._building:
  336. raise ValueError("Cyclic dependency while building %s" % (
  337. depname,
  338. ))
  339. hs._building[depname] = 1
  340. dep = builder()
  341. setattr(hs, depname, dep)
  342. del hs._building[depname]
  343. return dep
  344. raise NotImplementedError(
  345. "%s has no %s nor a builder for it" % (
  346. type(hs).__name__, depname,
  347. )
  348. )
  349. setattr(HomeServer, "get_%s" % (depname), _get)
  350. # Build magic accessors for every dependency
  351. for depname in HomeServer.DEPENDENCIES:
  352. _make_dependency_method(depname)