appservice.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2016 OpenMarket Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. import sys
  18. import synapse
  19. from synapse import events
  20. from synapse.app import _base
  21. from synapse.config._base import ConfigError
  22. from synapse.config.homeserver import HomeServerConfig
  23. from synapse.config.logger import setup_logging
  24. from synapse.http.site import SynapseSite
  25. from synapse.metrics.resource import METRICS_PREFIX, MetricsResource
  26. from synapse.replication.slave.storage.appservice import SlavedApplicationServiceStore
  27. from synapse.replication.slave.storage.directory import DirectoryStore
  28. from synapse.replication.slave.storage.events import SlavedEventStore
  29. from synapse.replication.slave.storage.registration import SlavedRegistrationStore
  30. from synapse.replication.tcp.client import ReplicationClientHandler
  31. from synapse.server import HomeServer
  32. from synapse.storage.engines import create_engine
  33. from synapse.util.httpresourcetree import create_resource_tree
  34. from synapse.util.logcontext import LoggingContext, preserve_fn
  35. from synapse.util.manhole import manhole
  36. from synapse.util.versionstring import get_version_string
  37. from twisted.internet import reactor
  38. from twisted.web.resource import NoResource
  39. logger = logging.getLogger("synapse.app.appservice")
  40. class AppserviceSlaveStore(
  41. DirectoryStore, SlavedEventStore, SlavedApplicationServiceStore,
  42. SlavedRegistrationStore,
  43. ):
  44. pass
  45. class AppserviceServer(HomeServer):
  46. def setup(self):
  47. logger.info("Setting up.")
  48. self.datastore = AppserviceSlaveStore(self.get_db_conn(), self)
  49. logger.info("Finished setting up.")
  50. def _listen_http(self, listener_config):
  51. port = listener_config["port"]
  52. bind_addresses = listener_config["bind_addresses"]
  53. site_tag = listener_config.get("tag", port)
  54. resources = {}
  55. for res in listener_config["resources"]:
  56. for name in res["names"]:
  57. if name == "metrics":
  58. resources[METRICS_PREFIX] = MetricsResource(self)
  59. root_resource = create_resource_tree(resources, NoResource())
  60. _base.listen_tcp(
  61. bind_addresses,
  62. port,
  63. SynapseSite(
  64. "synapse.access.http.%s" % (site_tag,),
  65. site_tag,
  66. listener_config,
  67. root_resource,
  68. )
  69. )
  70. logger.info("Synapse appservice now listening on port %d", port)
  71. def start_listening(self, listeners):
  72. for listener in listeners:
  73. if listener["type"] == "http":
  74. self._listen_http(listener)
  75. elif listener["type"] == "manhole":
  76. _base.listen_tcp(
  77. listener["bind_addresses"],
  78. listener["port"],
  79. manhole(
  80. username="matrix",
  81. password="rabbithole",
  82. globals={"hs": self},
  83. )
  84. )
  85. else:
  86. logger.warn("Unrecognized listener type: %s", listener["type"])
  87. self.get_tcp_replication().start_replication(self)
  88. def build_tcp_replication(self):
  89. return ASReplicationHandler(self)
  90. class ASReplicationHandler(ReplicationClientHandler):
  91. def __init__(self, hs):
  92. super(ASReplicationHandler, self).__init__(hs.get_datastore())
  93. self.appservice_handler = hs.get_application_service_handler()
  94. def on_rdata(self, stream_name, token, rows):
  95. super(ASReplicationHandler, self).on_rdata(stream_name, token, rows)
  96. if stream_name == "events":
  97. max_stream_id = self.store.get_room_max_stream_ordering()
  98. preserve_fn(
  99. self.appservice_handler.notify_interested_services
  100. )(max_stream_id)
  101. def start(config_options):
  102. try:
  103. config = HomeServerConfig.load_config(
  104. "Synapse appservice", config_options
  105. )
  106. except ConfigError as e:
  107. sys.stderr.write("\n" + e.message + "\n")
  108. sys.exit(1)
  109. assert config.worker_app == "synapse.app.appservice"
  110. setup_logging(config, use_worker_options=True)
  111. events.USE_FROZEN_DICTS = config.use_frozen_dicts
  112. database_engine = create_engine(config.database_config)
  113. if config.notify_appservices:
  114. sys.stderr.write(
  115. "\nThe appservices must be disabled in the main synapse process"
  116. "\nbefore they can be run in a separate worker."
  117. "\nPlease add ``notify_appservices: false`` to the main config"
  118. "\n"
  119. )
  120. sys.exit(1)
  121. # Force the pushers to start since they will be disabled in the main config
  122. config.notify_appservices = True
  123. ps = AppserviceServer(
  124. config.server_name,
  125. db_config=config.database_config,
  126. config=config,
  127. version_string="Synapse/" + get_version_string(synapse),
  128. database_engine=database_engine,
  129. )
  130. ps.setup()
  131. ps.start_listening(config.worker_listeners)
  132. def start():
  133. ps.get_datastore().start_profiling()
  134. ps.get_state_handler().start_caching()
  135. reactor.callWhenRunning(start)
  136. _base.start_worker_reactor("synapse-appservice", config)
  137. if __name__ == '__main__':
  138. with LoggingContext("main"):
  139. start(sys.argv[1:])