pusher.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. from twisted.internet import defer, reactor
  19. from twisted.web.resource import NoResource
  20. import synapse
  21. from synapse import events
  22. from synapse.app import _base
  23. from synapse.config._base import ConfigError
  24. from synapse.config.homeserver import HomeServerConfig
  25. from synapse.config.logger import setup_logging
  26. from synapse.http.site import SynapseSite
  27. from synapse.metrics import RegistryProxy
  28. from synapse.metrics.resource import METRICS_PREFIX, MetricsResource
  29. from synapse.replication.slave.storage.account_data import SlavedAccountDataStore
  30. from synapse.replication.slave.storage.events import SlavedEventStore
  31. from synapse.replication.slave.storage.pushers import SlavedPusherStore
  32. from synapse.replication.slave.storage.receipts import SlavedReceiptsStore
  33. from synapse.replication.tcp.client import ReplicationClientHandler
  34. from synapse.server import HomeServer
  35. from synapse.storage import DataStore
  36. from synapse.storage.engines import create_engine
  37. from synapse.util.httpresourcetree import create_resource_tree
  38. from synapse.util.logcontext import LoggingContext, run_in_background
  39. from synapse.util.manhole import manhole
  40. from synapse.util.versionstring import get_version_string
  41. logger = logging.getLogger("synapse.app.pusher")
  42. class PusherSlaveStore(
  43. SlavedEventStore, SlavedPusherStore, SlavedReceiptsStore,
  44. SlavedAccountDataStore
  45. ):
  46. update_pusher_last_stream_ordering_and_success = (
  47. DataStore.update_pusher_last_stream_ordering_and_success.__func__
  48. )
  49. update_pusher_failing_since = (
  50. DataStore.update_pusher_failing_since.__func__
  51. )
  52. update_pusher_last_stream_ordering = (
  53. DataStore.update_pusher_last_stream_ordering.__func__
  54. )
  55. get_throttle_params_by_room = (
  56. DataStore.get_throttle_params_by_room.__func__
  57. )
  58. set_throttle_params = (
  59. DataStore.set_throttle_params.__func__
  60. )
  61. get_time_of_last_push_action_before = (
  62. DataStore.get_time_of_last_push_action_before.__func__
  63. )
  64. get_profile_displayname = (
  65. DataStore.get_profile_displayname.__func__
  66. )
  67. class PusherServer(HomeServer):
  68. def setup(self):
  69. logger.info("Setting up.")
  70. self.datastore = PusherSlaveStore(self.get_db_conn(), self)
  71. logger.info("Finished setting up.")
  72. def remove_pusher(self, app_id, push_key, user_id):
  73. self.get_tcp_replication().send_remove_pusher(app_id, push_key, user_id)
  74. def _listen_http(self, listener_config):
  75. port = listener_config["port"]
  76. bind_addresses = listener_config["bind_addresses"]
  77. site_tag = listener_config.get("tag", port)
  78. resources = {}
  79. for res in listener_config["resources"]:
  80. for name in res["names"]:
  81. if name == "metrics":
  82. resources[METRICS_PREFIX] = MetricsResource(RegistryProxy)
  83. root_resource = create_resource_tree(resources, NoResource())
  84. _base.listen_tcp(
  85. bind_addresses,
  86. port,
  87. SynapseSite(
  88. "synapse.access.http.%s" % (site_tag,),
  89. site_tag,
  90. listener_config,
  91. root_resource,
  92. self.version_string,
  93. )
  94. )
  95. logger.info("Synapse pusher now listening on port %d", port)
  96. def start_listening(self, listeners):
  97. for listener in listeners:
  98. if listener["type"] == "http":
  99. self._listen_http(listener)
  100. elif listener["type"] == "manhole":
  101. _base.listen_tcp(
  102. listener["bind_addresses"],
  103. listener["port"],
  104. manhole(
  105. username="matrix",
  106. password="rabbithole",
  107. globals={"hs": self},
  108. )
  109. )
  110. elif listener["type"] == "metrics":
  111. if not self.get_config().enable_metrics:
  112. logger.warn(("Metrics listener configured, but "
  113. "enable_metrics is not True!"))
  114. else:
  115. _base.listen_metrics(listener["bind_addresses"],
  116. listener["port"])
  117. else:
  118. logger.warn("Unrecognized listener type: %s", listener["type"])
  119. self.get_tcp_replication().start_replication(self)
  120. def build_tcp_replication(self):
  121. return PusherReplicationHandler(self)
  122. class PusherReplicationHandler(ReplicationClientHandler):
  123. def __init__(self, hs):
  124. super(PusherReplicationHandler, self).__init__(hs.get_datastore())
  125. self.pusher_pool = hs.get_pusherpool()
  126. def on_rdata(self, stream_name, token, rows):
  127. super(PusherReplicationHandler, self).on_rdata(stream_name, token, rows)
  128. run_in_background(self.poke_pushers, stream_name, token, rows)
  129. @defer.inlineCallbacks
  130. def poke_pushers(self, stream_name, token, rows):
  131. try:
  132. if stream_name == "pushers":
  133. for row in rows:
  134. if row.deleted:
  135. yield self.stop_pusher(row.user_id, row.app_id, row.pushkey)
  136. else:
  137. yield self.start_pusher(row.user_id, row.app_id, row.pushkey)
  138. elif stream_name == "events":
  139. yield self.pusher_pool.on_new_notifications(
  140. token, token,
  141. )
  142. elif stream_name == "receipts":
  143. yield self.pusher_pool.on_new_receipts(
  144. token, token, set(row.room_id for row in rows)
  145. )
  146. except Exception:
  147. logger.exception("Error poking pushers")
  148. def stop_pusher(self, user_id, app_id, pushkey):
  149. key = "%s:%s" % (app_id, pushkey)
  150. pushers_for_user = self.pusher_pool.pushers.get(user_id, {})
  151. pusher = pushers_for_user.pop(key, None)
  152. if pusher is None:
  153. return
  154. logger.info("Stopping pusher %r / %r", user_id, key)
  155. pusher.on_stop()
  156. def start_pusher(self, user_id, app_id, pushkey):
  157. key = "%s:%s" % (app_id, pushkey)
  158. logger.info("Starting pusher %r / %r", user_id, key)
  159. return self.pusher_pool._refresh_pusher(app_id, pushkey, user_id)
  160. def start(config_options):
  161. try:
  162. config = HomeServerConfig.load_config(
  163. "Synapse pusher", config_options
  164. )
  165. except ConfigError as e:
  166. sys.stderr.write("\n" + e.message + "\n")
  167. sys.exit(1)
  168. assert config.worker_app == "synapse.app.pusher"
  169. setup_logging(config, use_worker_options=True)
  170. events.USE_FROZEN_DICTS = config.use_frozen_dicts
  171. if config.start_pushers:
  172. sys.stderr.write(
  173. "\nThe pushers must be disabled in the main synapse process"
  174. "\nbefore they can be run in a separate worker."
  175. "\nPlease add ``start_pushers: false`` to the main config"
  176. "\n"
  177. )
  178. sys.exit(1)
  179. # Force the pushers to start since they will be disabled in the main config
  180. config.start_pushers = True
  181. database_engine = create_engine(config.database_config)
  182. ps = PusherServer(
  183. config.server_name,
  184. db_config=config.database_config,
  185. config=config,
  186. version_string="Synapse/" + get_version_string(synapse),
  187. database_engine=database_engine,
  188. )
  189. ps.setup()
  190. ps.start_listening(config.worker_listeners)
  191. def start():
  192. ps.get_pusherpool().start()
  193. ps.get_datastore().start_profiling()
  194. ps.get_state_handler().start_caching()
  195. reactor.callWhenRunning(start)
  196. _base.start_worker_reactor("synapse-pusher", config)
  197. if __name__ == '__main__':
  198. with LoggingContext("main"):
  199. ps = start(sys.argv[1:])