pusherpool.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2015, 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. from typing import TYPE_CHECKING, Dict, Union
  18. from prometheus_client import Gauge
  19. from synapse.metrics.background_process_metrics import run_as_background_process
  20. from synapse.push import PusherConfigException
  21. from synapse.push.emailpusher import EmailPusher
  22. from synapse.push.httppusher import HttpPusher
  23. from synapse.push.pusher import PusherFactory
  24. from synapse.util.async_helpers import concurrently_execute
  25. if TYPE_CHECKING:
  26. from synapse.server import HomeServer
  27. logger = logging.getLogger(__name__)
  28. synapse_pushers = Gauge(
  29. "synapse_pushers", "Number of active synapse pushers", ["kind", "app_id"]
  30. )
  31. class PusherPool:
  32. """
  33. The pusher pool. This is responsible for dispatching notifications of new events to
  34. the http and email pushers.
  35. It provides three methods which are designed to be called by the rest of the
  36. application: `start`, `on_new_notifications`, and `on_new_receipts`: each of these
  37. delegates to each of the relevant pushers.
  38. Note that it is expected that each pusher will have its own 'processing' loop which
  39. will send out the notifications in the background, rather than blocking until the
  40. notifications are sent; accordingly Pusher.on_started, Pusher.on_new_notifications and
  41. Pusher.on_new_receipts are not expected to return awaitables.
  42. """
  43. def __init__(self, hs: "HomeServer"):
  44. self.hs = hs
  45. self.pusher_factory = PusherFactory(hs)
  46. self._should_start_pushers = hs.config.start_pushers
  47. self.store = self.hs.get_datastore()
  48. self.clock = self.hs.get_clock()
  49. self._account_validity = hs.config.account_validity
  50. # We shard the handling of push notifications by user ID.
  51. self._pusher_shard_config = hs.config.push.pusher_shard_config
  52. self._instance_name = hs.get_instance_name()
  53. # Record the last stream ID that we were poked about so we can get
  54. # changes since then. We set this to the current max stream ID on
  55. # startup as every individual pusher will have checked for changes on
  56. # startup.
  57. self._last_room_stream_id_seen = self.store.get_room_max_stream_ordering()
  58. # map from user id to app_id:pushkey to pusher
  59. self.pushers = {} # type: Dict[str, Dict[str, Union[HttpPusher, EmailPusher]]]
  60. def start(self):
  61. """Starts the pushers off in a background process.
  62. """
  63. if not self._should_start_pushers:
  64. logger.info("Not starting pushers because they are disabled in the config")
  65. return
  66. run_as_background_process("start_pushers", self._start_pushers)
  67. async def add_pusher(
  68. self,
  69. user_id,
  70. access_token,
  71. kind,
  72. app_id,
  73. app_display_name,
  74. device_display_name,
  75. pushkey,
  76. lang,
  77. data,
  78. profile_tag="",
  79. ):
  80. """Creates a new pusher and adds it to the pool
  81. Returns:
  82. EmailPusher|HttpPusher
  83. """
  84. time_now_msec = self.clock.time_msec()
  85. # we try to create the pusher just to validate the config: it
  86. # will then get pulled out of the database,
  87. # recreated, added and started: this means we have only one
  88. # code path adding pushers.
  89. self.pusher_factory.create_pusher(
  90. {
  91. "id": None,
  92. "user_name": user_id,
  93. "kind": kind,
  94. "app_id": app_id,
  95. "app_display_name": app_display_name,
  96. "device_display_name": device_display_name,
  97. "pushkey": pushkey,
  98. "ts": time_now_msec,
  99. "lang": lang,
  100. "data": data,
  101. "last_stream_ordering": None,
  102. "last_success": None,
  103. "failing_since": None,
  104. }
  105. )
  106. # create the pusher setting last_stream_ordering to the current maximum
  107. # stream ordering in event_push_actions, so it will process
  108. # pushes from this point onwards.
  109. last_stream_ordering = await self.store.get_latest_push_action_stream_ordering()
  110. await self.store.add_pusher(
  111. user_id=user_id,
  112. access_token=access_token,
  113. kind=kind,
  114. app_id=app_id,
  115. app_display_name=app_display_name,
  116. device_display_name=device_display_name,
  117. pushkey=pushkey,
  118. pushkey_ts=time_now_msec,
  119. lang=lang,
  120. data=data,
  121. last_stream_ordering=last_stream_ordering,
  122. profile_tag=profile_tag,
  123. )
  124. pusher = await self.start_pusher_by_id(app_id, pushkey, user_id)
  125. return pusher
  126. async def remove_pushers_by_app_id_and_pushkey_not_user(
  127. self, app_id, pushkey, not_user_id
  128. ):
  129. to_remove = await self.store.get_pushers_by_app_id_and_pushkey(app_id, pushkey)
  130. for p in to_remove:
  131. if p["user_name"] != not_user_id:
  132. logger.info(
  133. "Removing pusher for app id %s, pushkey %s, user %s",
  134. app_id,
  135. pushkey,
  136. p["user_name"],
  137. )
  138. await self.remove_pusher(p["app_id"], p["pushkey"], p["user_name"])
  139. async def remove_pushers_by_access_token(self, user_id, access_tokens):
  140. """Remove the pushers for a given user corresponding to a set of
  141. access_tokens.
  142. Args:
  143. user_id (str): user to remove pushers for
  144. access_tokens (Iterable[int]): access token *ids* to remove pushers
  145. for
  146. """
  147. if not self._pusher_shard_config.should_handle(self._instance_name, user_id):
  148. return
  149. tokens = set(access_tokens)
  150. for p in await self.store.get_pushers_by_user_id(user_id):
  151. if p["access_token"] in tokens:
  152. logger.info(
  153. "Removing pusher for app id %s, pushkey %s, user %s",
  154. p["app_id"],
  155. p["pushkey"],
  156. p["user_name"],
  157. )
  158. await self.remove_pusher(p["app_id"], p["pushkey"], p["user_name"])
  159. async def on_new_notifications(self, max_stream_id: int):
  160. if not self.pushers:
  161. # nothing to do here.
  162. return
  163. if max_stream_id < self._last_room_stream_id_seen:
  164. # Nothing to do
  165. return
  166. prev_stream_id = self._last_room_stream_id_seen
  167. self._last_room_stream_id_seen = max_stream_id
  168. try:
  169. users_affected = await self.store.get_push_action_users_in_range(
  170. prev_stream_id, max_stream_id
  171. )
  172. for u in users_affected:
  173. # Don't push if the user account has expired
  174. if self._account_validity.enabled:
  175. expired = await self.store.is_account_expired(
  176. u, self.clock.time_msec()
  177. )
  178. if expired:
  179. continue
  180. if u in self.pushers:
  181. for p in self.pushers[u].values():
  182. p.on_new_notifications(max_stream_id)
  183. except Exception:
  184. logger.exception("Exception in pusher on_new_notifications")
  185. async def on_new_receipts(self, min_stream_id, max_stream_id, affected_room_ids):
  186. if not self.pushers:
  187. # nothing to do here.
  188. return
  189. try:
  190. # Need to subtract 1 from the minimum because the lower bound here
  191. # is not inclusive
  192. users_affected = await self.store.get_users_sent_receipts_between(
  193. min_stream_id - 1, max_stream_id
  194. )
  195. for u in users_affected:
  196. # Don't push if the user account has expired
  197. if self._account_validity.enabled:
  198. expired = await self.store.is_account_expired(
  199. u, self.clock.time_msec()
  200. )
  201. if expired:
  202. continue
  203. if u in self.pushers:
  204. for p in self.pushers[u].values():
  205. p.on_new_receipts(min_stream_id, max_stream_id)
  206. except Exception:
  207. logger.exception("Exception in pusher on_new_receipts")
  208. async def start_pusher_by_id(self, app_id, pushkey, user_id):
  209. """Look up the details for the given pusher, and start it
  210. Returns:
  211. EmailPusher|HttpPusher|None: The pusher started, if any
  212. """
  213. if not self._should_start_pushers:
  214. return
  215. if not self._pusher_shard_config.should_handle(self._instance_name, user_id):
  216. return
  217. resultlist = await self.store.get_pushers_by_app_id_and_pushkey(app_id, pushkey)
  218. pusher_dict = None
  219. for r in resultlist:
  220. if r["user_name"] == user_id:
  221. pusher_dict = r
  222. pusher = None
  223. if pusher_dict:
  224. pusher = await self._start_pusher(pusher_dict)
  225. return pusher
  226. async def _start_pushers(self) -> None:
  227. """Start all the pushers
  228. """
  229. pushers = await self.store.get_all_pushers()
  230. # Stagger starting up the pushers so we don't completely drown the
  231. # process on start up.
  232. await concurrently_execute(self._start_pusher, pushers, 10)
  233. logger.info("Started pushers")
  234. async def _start_pusher(self, pusherdict):
  235. """Start the given pusher
  236. Args:
  237. pusherdict (dict): dict with the values pulled from the db table
  238. Returns:
  239. EmailPusher|HttpPusher
  240. """
  241. if not self._pusher_shard_config.should_handle(
  242. self._instance_name, pusherdict["user_name"]
  243. ):
  244. return
  245. try:
  246. p = self.pusher_factory.create_pusher(pusherdict)
  247. except PusherConfigException as e:
  248. logger.warning(
  249. "Pusher incorrectly configured id=%i, user=%s, appid=%s, pushkey=%s: %s",
  250. pusherdict["id"],
  251. pusherdict.get("user_name"),
  252. pusherdict.get("app_id"),
  253. pusherdict.get("pushkey"),
  254. e,
  255. )
  256. return
  257. except Exception:
  258. logger.exception(
  259. "Couldn't start pusher id %i: caught Exception", pusherdict["id"],
  260. )
  261. return
  262. if not p:
  263. return
  264. appid_pushkey = "%s:%s" % (pusherdict["app_id"], pusherdict["pushkey"])
  265. byuser = self.pushers.setdefault(pusherdict["user_name"], {})
  266. if appid_pushkey in byuser:
  267. byuser[appid_pushkey].on_stop()
  268. byuser[appid_pushkey] = p
  269. synapse_pushers.labels(type(p).__name__, p.app_id).inc()
  270. # Check if there *may* be push to process. We do this as this check is a
  271. # lot cheaper to do than actually fetching the exact rows we need to
  272. # push.
  273. user_id = pusherdict["user_name"]
  274. last_stream_ordering = pusherdict["last_stream_ordering"]
  275. if last_stream_ordering:
  276. have_notifs = await self.store.get_if_maybe_push_in_range_for_user(
  277. user_id, last_stream_ordering
  278. )
  279. else:
  280. # We always want to default to starting up the pusher rather than
  281. # risk missing push.
  282. have_notifs = True
  283. p.on_started(have_notifs)
  284. return p
  285. async def remove_pusher(self, app_id, pushkey, user_id):
  286. appid_pushkey = "%s:%s" % (app_id, pushkey)
  287. byuser = self.pushers.get(user_id, {})
  288. if appid_pushkey in byuser:
  289. logger.info("Stopping pusher %s / %s", user_id, appid_pushkey)
  290. pusher = byuser.pop(appid_pushkey)
  291. pusher.on_stop()
  292. synapse_pushers.labels(type(pusher).__name__, pusher.app_id).dec()
  293. await self.store.delete_pusher_by_app_id_pushkey_user_id(
  294. app_id, pushkey, user_id
  295. )