server.py 16 KB

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