pusher.py 7.9 KB

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