server.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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.federation import initialize_http_replication
  30. from synapse.federation.send_queue import FederationRemoteSendQueue
  31. from synapse.federation.transport.client import TransportLayerClient
  32. from synapse.federation.transaction_queue import TransactionQueue
  33. from synapse.handlers import Handlers
  34. from synapse.handlers.appservice import ApplicationServicesHandler
  35. from synapse.handlers.auth import AuthHandler
  36. from synapse.handlers.devicemessage import DeviceMessageHandler
  37. from synapse.handlers.device import DeviceHandler
  38. from synapse.handlers.e2e_keys import E2eKeysHandler
  39. from synapse.handlers.presence import PresenceHandler
  40. from synapse.handlers.room_list import RoomListHandler
  41. from synapse.handlers.sync import SyncHandler
  42. from synapse.handlers.typing import TypingHandler
  43. from synapse.handlers.events import EventHandler, EventStreamHandler
  44. from synapse.handlers.initial_sync import InitialSyncHandler
  45. from synapse.http.client import SimpleHttpClient, InsecureInterceptableContextFactory
  46. from synapse.http.matrixfederationclient import MatrixFederationHttpClient
  47. from synapse.notifier import Notifier
  48. from synapse.push.pusherpool import PusherPool
  49. from synapse.rest.media.v1.media_repository import MediaRepository
  50. from synapse.state import StateHandler
  51. from synapse.storage import DataStore
  52. from synapse.streams.events import EventSources
  53. from synapse.util import Clock
  54. from synapse.util.distributor import Distributor
  55. logger = logging.getLogger(__name__)
  56. class HomeServer(object):
  57. """A basic homeserver object without lazy component builders.
  58. This will need all of the components it requires to either be passed as
  59. constructor arguments, or the relevant methods overriding to create them.
  60. Typically this would only be used for unit tests.
  61. For every dependency in the DEPENDENCIES list below, this class creates one
  62. method,
  63. def get_DEPENDENCY(self)
  64. which returns the value of that dependency. If no value has yet been set
  65. nor was provided to the constructor, it will attempt to call a lazy builder
  66. method called
  67. def build_DEPENDENCY(self)
  68. which must be implemented by the subclass. This code may call any of the
  69. required "get" methods on the instance to obtain the sub-dependencies that
  70. one requires.
  71. """
  72. DEPENDENCIES = [
  73. 'config',
  74. 'clock',
  75. 'http_client',
  76. 'db_pool',
  77. 'persistence_service',
  78. 'replication_layer',
  79. 'datastore',
  80. 'handlers',
  81. 'v1auth',
  82. 'auth',
  83. 'rest_servlet_factory',
  84. 'state_handler',
  85. 'presence_handler',
  86. 'sync_handler',
  87. 'typing_handler',
  88. 'room_list_handler',
  89. 'auth_handler',
  90. 'device_handler',
  91. 'e2e_keys_handler',
  92. 'event_handler',
  93. 'event_stream_handler',
  94. 'initial_sync_handler',
  95. 'application_service_api',
  96. 'application_service_scheduler',
  97. 'application_service_handler',
  98. 'device_message_handler',
  99. 'notifier',
  100. 'distributor',
  101. 'client_resource',
  102. 'resource_for_federation',
  103. 'resource_for_static_content',
  104. 'resource_for_web_client',
  105. 'resource_for_content_repo',
  106. 'resource_for_server_key',
  107. 'resource_for_server_key_v2',
  108. 'resource_for_media_repository',
  109. 'resource_for_metrics',
  110. 'event_sources',
  111. 'ratelimiter',
  112. 'keyring',
  113. 'pusherpool',
  114. 'event_builder_factory',
  115. 'filtering',
  116. 'http_client_context_factory',
  117. 'simple_http_client',
  118. 'media_repository',
  119. 'federation_transport_client',
  120. 'federation_sender',
  121. ]
  122. def __init__(self, hostname, **kwargs):
  123. """
  124. Args:
  125. hostname : The hostname for the server.
  126. """
  127. self.hostname = hostname
  128. self._building = {}
  129. self.clock = Clock()
  130. self.distributor = Distributor()
  131. self.ratelimiter = Ratelimiter()
  132. # Other kwargs are explicit dependencies
  133. for depname in kwargs:
  134. setattr(self, depname, kwargs[depname])
  135. def setup(self):
  136. logger.info("Setting up.")
  137. self.datastore = DataStore(self.get_db_conn(), self)
  138. logger.info("Finished setting up.")
  139. def get_ip_from_request(self, request):
  140. # X-Forwarded-For is handled by our custom request type.
  141. return request.getClientIP()
  142. def is_mine(self, domain_specific_string):
  143. return domain_specific_string.domain == self.hostname
  144. def is_mine_id(self, string):
  145. return string.split(":", 1)[1] == self.hostname
  146. def build_replication_layer(self):
  147. return initialize_http_replication(self)
  148. def build_handlers(self):
  149. return Handlers(self)
  150. def build_notifier(self):
  151. return Notifier(self)
  152. def build_auth(self):
  153. return Auth(self)
  154. def build_http_client_context_factory(self):
  155. return (
  156. InsecureInterceptableContextFactory()
  157. if self.config.use_insecure_ssl_client_just_for_testing_do_not_use
  158. else BrowserLikePolicyForHTTPS()
  159. )
  160. def build_simple_http_client(self):
  161. return SimpleHttpClient(self)
  162. def build_v1auth(self):
  163. orf = Auth(self)
  164. # Matrix spec makes no reference to what HTTP status code is returned,
  165. # but the V1 API uses 403 where it means 401, and the webclient
  166. # relies on this behaviour, so V1 gets its own copy of the auth
  167. # with backwards compat behaviour.
  168. orf.TOKEN_NOT_FOUND_HTTP_STATUS = 403
  169. return orf
  170. def build_state_handler(self):
  171. return StateHandler(self)
  172. def build_presence_handler(self):
  173. return PresenceHandler(self)
  174. def build_typing_handler(self):
  175. return TypingHandler(self)
  176. def build_sync_handler(self):
  177. return SyncHandler(self)
  178. def build_room_list_handler(self):
  179. return RoomListHandler(self)
  180. def build_auth_handler(self):
  181. return AuthHandler(self)
  182. def build_device_handler(self):
  183. return DeviceHandler(self)
  184. def build_device_message_handler(self):
  185. return DeviceMessageHandler(self)
  186. def build_e2e_keys_handler(self):
  187. return E2eKeysHandler(self)
  188. def build_application_service_api(self):
  189. return ApplicationServiceApi(self)
  190. def build_application_service_scheduler(self):
  191. return ApplicationServiceScheduler(self)
  192. def build_application_service_handler(self):
  193. return ApplicationServicesHandler(self)
  194. def build_event_handler(self):
  195. return EventHandler(self)
  196. def build_event_stream_handler(self):
  197. return EventStreamHandler(self)
  198. def build_initial_sync_handler(self):
  199. return InitialSyncHandler(self)
  200. def build_event_sources(self):
  201. return EventSources(self)
  202. def build_keyring(self):
  203. return Keyring(self)
  204. def build_event_builder_factory(self):
  205. return EventBuilderFactory(
  206. clock=self.get_clock(),
  207. hostname=self.hostname,
  208. )
  209. def build_filtering(self):
  210. return Filtering(self)
  211. def build_pusherpool(self):
  212. return PusherPool(self)
  213. def build_http_client(self):
  214. return MatrixFederationHttpClient(self)
  215. def build_db_pool(self):
  216. name = self.db_config["name"]
  217. return adbapi.ConnectionPool(
  218. name,
  219. **self.db_config.get("args", {})
  220. )
  221. def build_media_repository(self):
  222. return MediaRepository(self)
  223. def build_federation_transport_client(self):
  224. return TransportLayerClient(self)
  225. def build_federation_sender(self):
  226. if self.config.send_federation:
  227. return TransactionQueue(self)
  228. else:
  229. return FederationRemoteSendQueue(self)
  230. def remove_pusher(self, app_id, push_key, user_id):
  231. return self.get_pusherpool().remove_pusher(app_id, push_key, user_id)
  232. def _make_dependency_method(depname):
  233. def _get(hs):
  234. try:
  235. return getattr(hs, depname)
  236. except AttributeError:
  237. pass
  238. try:
  239. builder = getattr(hs, "build_%s" % (depname))
  240. except AttributeError:
  241. builder = None
  242. if builder:
  243. # Prevent cyclic dependencies from deadlocking
  244. if depname in hs._building:
  245. raise ValueError("Cyclic dependency while building %s" % (
  246. depname,
  247. ))
  248. hs._building[depname] = 1
  249. dep = builder()
  250. setattr(hs, depname, dep)
  251. del hs._building[depname]
  252. return dep
  253. raise NotImplementedError(
  254. "%s has no %s nor a builder for it" % (
  255. type(hs).__name__, depname,
  256. )
  257. )
  258. setattr(HomeServer, "get_%s" % (depname), _get)
  259. # Build magic accessors for every dependency
  260. for depname in HomeServer.DEPENDENCIES:
  261. _make_dependency_method(depname)