server.py 8.5 KB

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