appservice.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from six import itervalues
  17. from prometheus_client import Counter
  18. from twisted.internet import defer
  19. import synapse
  20. from synapse.api.constants import EventTypes
  21. from synapse.logging.context import make_deferred_yieldable, run_in_background
  22. from synapse.metrics import (
  23. event_processing_loop_counter,
  24. event_processing_loop_room_count,
  25. )
  26. from synapse.metrics.background_process_metrics import run_as_background_process
  27. from synapse.util import log_failure
  28. from synapse.util.metrics import Measure
  29. logger = logging.getLogger(__name__)
  30. events_processed_counter = Counter("synapse_handlers_appservice_events_processed", "")
  31. class ApplicationServicesHandler(object):
  32. def __init__(self, hs):
  33. self.store = hs.get_datastore()
  34. self.is_mine_id = hs.is_mine_id
  35. self.appservice_api = hs.get_application_service_api()
  36. self.scheduler = hs.get_application_service_scheduler()
  37. self.started_scheduler = False
  38. self.clock = hs.get_clock()
  39. self.notify_appservices = hs.config.notify_appservices
  40. self.current_max = 0
  41. self.is_processing = False
  42. @defer.inlineCallbacks
  43. def notify_interested_services(self, current_id):
  44. """Notifies (pushes) all application services interested in this event.
  45. Pushing is done asynchronously, so this method won't block for any
  46. prolonged length of time.
  47. Args:
  48. current_id(int): The current maximum ID.
  49. """
  50. services = self.store.get_app_services()
  51. if not services or not self.notify_appservices:
  52. return
  53. self.current_max = max(self.current_max, current_id)
  54. if self.is_processing:
  55. return
  56. with Measure(self.clock, "notify_interested_services"):
  57. self.is_processing = True
  58. try:
  59. limit = 100
  60. while True:
  61. (
  62. upper_bound,
  63. events,
  64. ) = yield self.store.get_new_events_for_appservice(
  65. self.current_max, limit
  66. )
  67. if not events:
  68. break
  69. events_by_room = {}
  70. for event in events:
  71. events_by_room.setdefault(event.room_id, []).append(event)
  72. @defer.inlineCallbacks
  73. def handle_event(event):
  74. # Gather interested services
  75. services = yield self._get_services_for_event(event)
  76. if len(services) == 0:
  77. return # no services need notifying
  78. # Do we know this user exists? If not, poke the user
  79. # query API for all services which match that user regex.
  80. # This needs to block as these user queries need to be
  81. # made BEFORE pushing the event.
  82. yield self._check_user_exists(event.sender)
  83. if event.type == EventTypes.Member:
  84. yield self._check_user_exists(event.state_key)
  85. if not self.started_scheduler:
  86. def start_scheduler():
  87. return self.scheduler.start().addErrback(
  88. log_failure, "Application Services Failure"
  89. )
  90. run_as_background_process("as_scheduler", start_scheduler)
  91. self.started_scheduler = True
  92. # Fork off pushes to these services
  93. for service in services:
  94. self.scheduler.submit_event_for_as(service, event)
  95. @defer.inlineCallbacks
  96. def handle_room_events(events):
  97. for event in events:
  98. yield handle_event(event)
  99. yield make_deferred_yieldable(
  100. defer.gatherResults(
  101. [
  102. run_in_background(handle_room_events, evs)
  103. for evs in itervalues(events_by_room)
  104. ],
  105. consumeErrors=True,
  106. )
  107. )
  108. yield self.store.set_appservice_last_pos(upper_bound)
  109. now = self.clock.time_msec()
  110. ts = yield self.store.get_received_ts(events[-1].event_id)
  111. synapse.metrics.event_processing_positions.labels(
  112. "appservice_sender"
  113. ).set(upper_bound)
  114. events_processed_counter.inc(len(events))
  115. event_processing_loop_room_count.labels("appservice_sender").inc(
  116. len(events_by_room)
  117. )
  118. event_processing_loop_counter.labels("appservice_sender").inc()
  119. synapse.metrics.event_processing_lag.labels(
  120. "appservice_sender"
  121. ).set(now - ts)
  122. synapse.metrics.event_processing_last_ts.labels(
  123. "appservice_sender"
  124. ).set(ts)
  125. finally:
  126. self.is_processing = False
  127. @defer.inlineCallbacks
  128. def query_user_exists(self, user_id):
  129. """Check if any application service knows this user_id exists.
  130. Args:
  131. user_id(str): The user to query if they exist on any AS.
  132. Returns:
  133. True if this user exists on at least one application service.
  134. """
  135. user_query_services = yield self._get_services_for_user(user_id=user_id)
  136. for user_service in user_query_services:
  137. is_known_user = yield self.appservice_api.query_user(user_service, user_id)
  138. if is_known_user:
  139. return True
  140. return False
  141. @defer.inlineCallbacks
  142. def query_room_alias_exists(self, room_alias):
  143. """Check if an application service knows this room alias exists.
  144. Args:
  145. room_alias(RoomAlias): The room alias to query.
  146. Returns:
  147. namedtuple: with keys "room_id" and "servers" or None if no
  148. association can be found.
  149. """
  150. room_alias_str = room_alias.to_string()
  151. services = self.store.get_app_services()
  152. alias_query_services = [
  153. s for s in services if (s.is_interested_in_alias(room_alias_str))
  154. ]
  155. for alias_service in alias_query_services:
  156. is_known_alias = yield self.appservice_api.query_alias(
  157. alias_service, room_alias_str
  158. )
  159. if is_known_alias:
  160. # the alias exists now so don't query more ASes.
  161. result = yield self.store.get_association_from_room_alias(room_alias)
  162. return result
  163. @defer.inlineCallbacks
  164. def query_3pe(self, kind, protocol, fields):
  165. services = yield self._get_services_for_3pn(protocol)
  166. results = yield make_deferred_yieldable(
  167. defer.DeferredList(
  168. [
  169. run_in_background(
  170. self.appservice_api.query_3pe, service, kind, protocol, fields
  171. )
  172. for service in services
  173. ],
  174. consumeErrors=True,
  175. )
  176. )
  177. ret = []
  178. for (success, result) in results:
  179. if success:
  180. ret.extend(result)
  181. return ret
  182. @defer.inlineCallbacks
  183. def get_3pe_protocols(self, only_protocol=None):
  184. services = self.store.get_app_services()
  185. protocols = {}
  186. # Collect up all the individual protocol responses out of the ASes
  187. for s in services:
  188. for p in s.protocols:
  189. if only_protocol is not None and p != only_protocol:
  190. continue
  191. if p not in protocols:
  192. protocols[p] = []
  193. info = yield self.appservice_api.get_3pe_protocol(s, p)
  194. if info is not None:
  195. protocols[p].append(info)
  196. def _merge_instances(infos):
  197. if not infos:
  198. return {}
  199. # Merge the 'instances' lists of multiple results, but just take
  200. # the other fields from the first as they ought to be identical
  201. # copy the result so as not to corrupt the cached one
  202. combined = dict(infos[0])
  203. combined["instances"] = list(combined["instances"])
  204. for info in infos[1:]:
  205. combined["instances"].extend(info["instances"])
  206. return combined
  207. for p in protocols.keys():
  208. protocols[p] = _merge_instances(protocols[p])
  209. return protocols
  210. @defer.inlineCallbacks
  211. def _get_services_for_event(self, event):
  212. """Retrieve a list of application services interested in this event.
  213. Args:
  214. event(Event): The event to check. Can be None if alias_list is not.
  215. Returns:
  216. list<ApplicationService>: A list of services interested in this
  217. event based on the service regex.
  218. """
  219. services = self.store.get_app_services()
  220. # we can't use a list comprehension here. Since python 3, list
  221. # comprehensions use a generator internally. This means you can't yield
  222. # inside of a list comprehension anymore.
  223. interested_list = []
  224. for s in services:
  225. if (yield s.is_interested(event, self.store)):
  226. interested_list.append(s)
  227. return interested_list
  228. def _get_services_for_user(self, user_id):
  229. services = self.store.get_app_services()
  230. interested_list = [s for s in services if (s.is_interested_in_user(user_id))]
  231. return defer.succeed(interested_list)
  232. def _get_services_for_3pn(self, protocol):
  233. services = self.store.get_app_services()
  234. interested_list = [s for s in services if s.is_interested_in_protocol(protocol)]
  235. return defer.succeed(interested_list)
  236. @defer.inlineCallbacks
  237. def _is_unknown_user(self, user_id):
  238. if not self.is_mine_id(user_id):
  239. # we don't know if they are unknown or not since it isn't one of our
  240. # users. We can't poke ASes.
  241. return False
  242. user_info = yield self.store.get_user_by_id(user_id)
  243. if user_info:
  244. return False
  245. # user not found; could be the AS though, so check.
  246. services = self.store.get_app_services()
  247. service_list = [s for s in services if s.sender == user_id]
  248. return len(service_list) == 0
  249. @defer.inlineCallbacks
  250. def _check_user_exists(self, user_id):
  251. unknown_user = yield self._is_unknown_user(user_id)
  252. if unknown_user:
  253. exists = yield self.query_user_exists(user_id)
  254. return exists
  255. return True