server.py 7.2 KB

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