您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

468 行
17 KiB

  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import TYPE_CHECKING, Dict, Iterable, Optional
  16. from prometheus_client import Gauge
  17. from synapse.api.errors import Codes, SynapseError
  18. from synapse.metrics.background_process_metrics import (
  19. run_as_background_process,
  20. wrap_as_background_process,
  21. )
  22. from synapse.push import Pusher, PusherConfig, PusherConfigException
  23. from synapse.push.pusher import PusherFactory
  24. from synapse.replication.http.push import ReplicationRemovePusherRestServlet
  25. from synapse.types import JsonDict, RoomStreamToken, StrCollection
  26. from synapse.util.async_helpers import concurrently_execute
  27. from synapse.util.threepids import canonicalise_email
  28. if TYPE_CHECKING:
  29. from synapse.server import HomeServer
  30. logger = logging.getLogger(__name__)
  31. synapse_pushers = Gauge(
  32. "synapse_pushers", "Number of active synapse pushers", ["kind", "app_id"]
  33. )
  34. class PusherPool:
  35. """
  36. The pusher pool. This is responsible for dispatching notifications of new events to
  37. the http and email pushers.
  38. It provides three methods which are designed to be called by the rest of the
  39. application: `start`, `on_new_notifications`, and `on_new_receipts`: each of these
  40. delegates to each of the relevant pushers.
  41. Note that it is expected that each pusher will have its own 'processing' loop which
  42. will send out the notifications in the background, rather than blocking until the
  43. notifications are sent; accordingly Pusher.on_started, Pusher.on_new_notifications and
  44. Pusher.on_new_receipts are not expected to return awaitables.
  45. """
  46. def __init__(self, hs: "HomeServer"):
  47. self.hs = hs
  48. self.pusher_factory = PusherFactory(hs)
  49. self.store = self.hs.get_datastores().main
  50. self.clock = self.hs.get_clock()
  51. # We shard the handling of push notifications by user ID.
  52. self._pusher_shard_config = hs.config.worker.pusher_shard_config
  53. self._instance_name = hs.get_instance_name()
  54. self._should_start_pushers = (
  55. self._instance_name in self._pusher_shard_config.instances
  56. )
  57. # We can only delete pushers on master.
  58. self._remove_pusher_client = None
  59. if hs.config.worker.worker_app:
  60. self._remove_pusher_client = ReplicationRemovePusherRestServlet.make_client(
  61. hs
  62. )
  63. # Record the last stream ID that we were poked about so we can get
  64. # changes since then. We set this to the current max stream ID on
  65. # startup as every individual pusher will have checked for changes on
  66. # startup.
  67. self._last_room_stream_id_seen = self.store.get_room_max_stream_ordering()
  68. # map from user id to app_id:pushkey to pusher
  69. self.pushers: Dict[str, Dict[str, Pusher]] = {}
  70. self._account_validity_handler = hs.get_account_validity_handler()
  71. def start(self) -> None:
  72. """Starts the pushers off in a background process."""
  73. if not self._should_start_pushers:
  74. logger.info("Not starting pushers because they are disabled in the config")
  75. return
  76. run_as_background_process("start_pushers", self._start_pushers)
  77. async def add_or_update_pusher(
  78. self,
  79. user_id: str,
  80. kind: str,
  81. app_id: str,
  82. app_display_name: str,
  83. device_display_name: str,
  84. pushkey: str,
  85. lang: Optional[str],
  86. data: JsonDict,
  87. profile_tag: str = "",
  88. enabled: bool = True,
  89. device_id: Optional[str] = None,
  90. ) -> Optional[Pusher]:
  91. """Creates a new pusher and adds it to the pool
  92. Returns:
  93. The newly created pusher.
  94. """
  95. if kind == "email":
  96. email_owner = await self.store.get_user_id_by_threepid(
  97. "email", canonicalise_email(pushkey)
  98. )
  99. if email_owner != user_id:
  100. raise SynapseError(400, "Email not found", Codes.THREEPID_NOT_FOUND)
  101. time_now_msec = self.clock.time_msec()
  102. # create the pusher setting last_stream_ordering to the current maximum
  103. # stream ordering, so it will process pushes from this point onwards.
  104. last_stream_ordering = self.store.get_room_max_stream_ordering()
  105. # Before we actually persist the pusher, we check if the user already has one
  106. # for this app ID and pushkey. If so, we want to keep the access token and
  107. # device ID in place, since this could be one device modifying
  108. # (e.g. enabling/disabling) another device's pusher.
  109. # XXX(quenting): Even though we're not persisting the access_token_id for new
  110. # pushers anymore, we still need to copy existing access_token_ids over when
  111. # updating a pusher, in case the "set_device_id_for_pushers" background update
  112. # hasn't run yet.
  113. access_token_id = None
  114. existing_config = await self._get_pusher_config_for_user_by_app_id_and_pushkey(
  115. user_id, app_id, pushkey
  116. )
  117. if existing_config:
  118. device_id = existing_config.device_id
  119. access_token_id = existing_config.access_token
  120. # we try to create the pusher just to validate the config: it
  121. # will then get pulled out of the database,
  122. # recreated, added and started: this means we have only one
  123. # code path adding pushers.
  124. self.pusher_factory.create_pusher(
  125. PusherConfig(
  126. id=None,
  127. user_name=user_id,
  128. profile_tag=profile_tag,
  129. kind=kind,
  130. app_id=app_id,
  131. app_display_name=app_display_name,
  132. device_display_name=device_display_name,
  133. pushkey=pushkey,
  134. ts=time_now_msec,
  135. lang=lang,
  136. data=data,
  137. last_stream_ordering=last_stream_ordering,
  138. last_success=None,
  139. failing_since=None,
  140. enabled=enabled,
  141. device_id=device_id,
  142. access_token=access_token_id,
  143. )
  144. )
  145. await self.store.add_pusher(
  146. user_id=user_id,
  147. kind=kind,
  148. app_id=app_id,
  149. app_display_name=app_display_name,
  150. device_display_name=device_display_name,
  151. pushkey=pushkey,
  152. pushkey_ts=time_now_msec,
  153. lang=lang,
  154. data=data,
  155. last_stream_ordering=last_stream_ordering,
  156. profile_tag=profile_tag,
  157. enabled=enabled,
  158. device_id=device_id,
  159. access_token_id=access_token_id,
  160. )
  161. pusher = await self.process_pusher_change_by_id(app_id, pushkey, user_id)
  162. return pusher
  163. async def remove_pushers_by_app_id_and_pushkey_not_user(
  164. self, app_id: str, pushkey: str, not_user_id: str
  165. ) -> None:
  166. to_remove = await self.store.get_pushers_by_app_id_and_pushkey(app_id, pushkey)
  167. for p in to_remove:
  168. if p.user_name != not_user_id:
  169. logger.info(
  170. "Removing pusher for app id %s, pushkey %s, user %s",
  171. app_id,
  172. pushkey,
  173. p.user_name,
  174. )
  175. await self.remove_pusher(p.app_id, p.pushkey, p.user_name)
  176. async def remove_pushers_by_access_tokens(
  177. self, user_id: str, access_tokens: Iterable[int]
  178. ) -> None:
  179. """Remove the pushers for a given user corresponding to a set of
  180. access_tokens.
  181. Args:
  182. user_id: user to remove pushers for
  183. access_tokens: access token *ids* to remove pushers for
  184. """
  185. # XXX(quenting): This is only needed until the "set_device_id_for_pushers"
  186. # background update finishes
  187. tokens = set(access_tokens)
  188. for p in await self.store.get_pushers_by_user_id(user_id):
  189. if p.access_token in tokens:
  190. logger.info(
  191. "Removing pusher for app id %s, pushkey %s, user %s",
  192. p.app_id,
  193. p.pushkey,
  194. p.user_name,
  195. )
  196. await self.remove_pusher(p.app_id, p.pushkey, p.user_name)
  197. async def remove_pushers_by_devices(
  198. self, user_id: str, devices: StrCollection
  199. ) -> None:
  200. """Remove the pushers for a given user corresponding to a set of devices
  201. Args:
  202. user_id: user to remove pushers for
  203. devices: device IDs to remove pushers for
  204. """
  205. device_ids = set(devices)
  206. for p in await self.store.get_pushers_by_user_id(user_id):
  207. if p.device_id in device_ids:
  208. logger.info(
  209. "Removing pusher for app id %s, pushkey %s, user %s",
  210. p.app_id,
  211. p.pushkey,
  212. p.user_name,
  213. )
  214. await self.remove_pusher(p.app_id, p.pushkey, p.user_name)
  215. def on_new_notifications(self, max_token: RoomStreamToken) -> None:
  216. if not self.pushers:
  217. # nothing to do here.
  218. return
  219. # We just use the minimum stream ordering and ignore the vector clock
  220. # component. This is safe to do as long as we *always* ignore the vector
  221. # clock components.
  222. max_stream_id = max_token.stream
  223. if max_stream_id < self._last_room_stream_id_seen:
  224. # Nothing to do
  225. return
  226. # We only start a new background process if necessary rather than
  227. # optimistically (to cut down on overhead).
  228. self._on_new_notifications(max_token)
  229. @wrap_as_background_process("on_new_notifications")
  230. async def _on_new_notifications(self, max_token: RoomStreamToken) -> None:
  231. # We just use the minimum stream ordering and ignore the vector clock
  232. # component. This is safe to do as long as we *always* ignore the vector
  233. # clock components.
  234. max_stream_id = max_token.stream
  235. prev_stream_id = self._last_room_stream_id_seen
  236. self._last_room_stream_id_seen = max_stream_id
  237. try:
  238. users_affected = await self.store.get_push_action_users_in_range(
  239. prev_stream_id, max_stream_id
  240. )
  241. for u in users_affected:
  242. # Don't push if the user account has expired
  243. expired = await self._account_validity_handler.is_user_expired(u)
  244. if expired:
  245. continue
  246. if u in self.pushers:
  247. for p in self.pushers[u].values():
  248. p.on_new_notifications(max_token)
  249. except Exception:
  250. logger.exception("Exception in pusher on_new_notifications")
  251. async def on_new_receipts(self, users_affected: StrCollection) -> None:
  252. if not self.pushers:
  253. # nothing to do here.
  254. return
  255. try:
  256. for u in users_affected:
  257. # Don't push if the user account has expired
  258. expired = await self._account_validity_handler.is_user_expired(u)
  259. if expired:
  260. continue
  261. if u in self.pushers:
  262. for p in self.pushers[u].values():
  263. p.on_new_receipts()
  264. except Exception:
  265. logger.exception("Exception in pusher on_new_receipts")
  266. async def _get_pusher_config_for_user_by_app_id_and_pushkey(
  267. self, user_id: str, app_id: str, pushkey: str
  268. ) -> Optional[PusherConfig]:
  269. resultlist = await self.store.get_pushers_by_app_id_and_pushkey(app_id, pushkey)
  270. pusher_config = None
  271. for r in resultlist:
  272. if r.user_name == user_id:
  273. pusher_config = r
  274. return pusher_config
  275. async def process_pusher_change_by_id(
  276. self, app_id: str, pushkey: str, user_id: str
  277. ) -> Optional[Pusher]:
  278. """Look up the details for the given pusher, and either start it if its
  279. "enabled" flag is True, or try to stop it otherwise.
  280. If the pusher is new and its "enabled" flag is False, the stop is a noop.
  281. Returns:
  282. The pusher started, if any
  283. """
  284. if not self._should_start_pushers:
  285. return None
  286. if not self._pusher_shard_config.should_handle(self._instance_name, user_id):
  287. return None
  288. pusher_config = await self._get_pusher_config_for_user_by_app_id_and_pushkey(
  289. user_id, app_id, pushkey
  290. )
  291. if pusher_config and not pusher_config.enabled:
  292. self.maybe_stop_pusher(app_id, pushkey, user_id)
  293. return None
  294. pusher = None
  295. if pusher_config:
  296. pusher = await self._start_pusher(pusher_config)
  297. return pusher
  298. async def _start_pushers(self) -> None:
  299. """Start all the pushers"""
  300. pushers = await self.store.get_enabled_pushers()
  301. # Stagger starting up the pushers so we don't completely drown the
  302. # process on start up.
  303. await concurrently_execute(self._start_pusher, pushers, 10)
  304. logger.info("Started pushers")
  305. async def _start_pusher(self, pusher_config: PusherConfig) -> Optional[Pusher]:
  306. """Start the given pusher
  307. Args:
  308. pusher_config: The pusher configuration with the values pulled from the db table
  309. Returns:
  310. The newly created pusher or None.
  311. """
  312. if not self._pusher_shard_config.should_handle(
  313. self._instance_name, pusher_config.user_name
  314. ):
  315. return None
  316. try:
  317. pusher = self.pusher_factory.create_pusher(pusher_config)
  318. except PusherConfigException as e:
  319. logger.warning(
  320. "Pusher incorrectly configured id=%i, user=%s, appid=%s, pushkey=%s: %s",
  321. pusher_config.id,
  322. pusher_config.user_name,
  323. pusher_config.app_id,
  324. pusher_config.pushkey,
  325. e,
  326. )
  327. return None
  328. except Exception:
  329. logger.exception(
  330. "Couldn't start pusher id %i: caught Exception",
  331. pusher_config.id,
  332. )
  333. return None
  334. if not pusher:
  335. return None
  336. appid_pushkey = "%s:%s" % (pusher.app_id, pusher.pushkey)
  337. byuser = self.pushers.setdefault(pusher.user_id, {})
  338. if appid_pushkey in byuser:
  339. previous_pusher = byuser[appid_pushkey]
  340. previous_pusher.on_stop()
  341. synapse_pushers.labels(
  342. type(previous_pusher).__name__, previous_pusher.app_id
  343. ).dec()
  344. byuser[appid_pushkey] = pusher
  345. synapse_pushers.labels(type(pusher).__name__, pusher.app_id).inc()
  346. logger.info("Starting pusher %s / %s", pusher.user_id, appid_pushkey)
  347. # Check if there *may* be push to process. We do this as this check is a
  348. # lot cheaper to do than actually fetching the exact rows we need to
  349. # push.
  350. user_id = pusher.user_id
  351. last_stream_ordering = pusher.last_stream_ordering
  352. if last_stream_ordering:
  353. have_notifs = await self.store.get_if_maybe_push_in_range_for_user(
  354. user_id, last_stream_ordering
  355. )
  356. else:
  357. # We always want to default to starting up the pusher rather than
  358. # risk missing push.
  359. have_notifs = True
  360. pusher.on_started(have_notifs)
  361. return pusher
  362. async def remove_pusher(self, app_id: str, pushkey: str, user_id: str) -> None:
  363. self.maybe_stop_pusher(app_id, pushkey, user_id)
  364. # We can only delete pushers on master.
  365. if self._remove_pusher_client:
  366. await self._remove_pusher_client(
  367. app_id=app_id, pushkey=pushkey, user_id=user_id
  368. )
  369. else:
  370. await self.store.delete_pusher_by_app_id_pushkey_user_id(
  371. app_id, pushkey, user_id
  372. )
  373. def maybe_stop_pusher(self, app_id: str, pushkey: str, user_id: str) -> None:
  374. """Stops a pusher with the given app ID and push key if one is running.
  375. Args:
  376. app_id: the pusher's app ID.
  377. pushkey: the pusher's push key.
  378. user_id: the user the pusher belongs to. Only used for logging.
  379. """
  380. appid_pushkey = "%s:%s" % (app_id, pushkey)
  381. byuser = self.pushers.get(user_id, {})
  382. if appid_pushkey in byuser:
  383. logger.info("Stopping pusher %s / %s", user_id, appid_pushkey)
  384. pusher = byuser.pop(appid_pushkey)
  385. pusher.on_stop()
  386. synapse_pushers.labels(type(pusher).__name__, pusher.app_id).dec()