server.py 6.6 KB

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