appservice.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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.metrics import (
  22. event_processing_loop_counter,
  23. event_processing_loop_room_count,
  24. )
  25. from synapse.metrics.background_process_metrics import run_as_background_process
  26. from synapse.util import log_failure
  27. from synapse.util.logcontext import make_deferred_yieldable, run_in_background
  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. upper_bound, events = yield self.store.get_new_events_for_appservice(
  62. self.current_max, limit
  63. )
  64. if not events:
  65. break
  66. events_by_room = {}
  67. for event in events:
  68. events_by_room.setdefault(event.room_id, []).append(event)
  69. @defer.inlineCallbacks
  70. def handle_event(event):
  71. # Gather interested services
  72. services = yield self._get_services_for_event(event)
  73. if len(services) == 0:
  74. return # no services need notifying
  75. # Do we know this user exists? If not, poke the user
  76. # query API for all services which match that user regex.
  77. # This needs to block as these user queries need to be
  78. # made BEFORE pushing the event.
  79. yield self._check_user_exists(event.sender)
  80. if event.type == EventTypes.Member:
  81. yield self._check_user_exists(event.state_key)
  82. if not self.started_scheduler:
  83. def start_scheduler():
  84. return self.scheduler.start().addErrback(
  85. log_failure, "Application Services Failure",
  86. )
  87. run_as_background_process("as_scheduler", start_scheduler)
  88. self.started_scheduler = True
  89. # Fork off pushes to these services
  90. for service in services:
  91. self.scheduler.submit_event_for_as(service, event)
  92. @defer.inlineCallbacks
  93. def handle_room_events(events):
  94. for event in events:
  95. yield handle_event(event)
  96. yield make_deferred_yieldable(defer.gatherResults([
  97. run_in_background(handle_room_events, evs)
  98. for evs in itervalues(events_by_room)
  99. ], consumeErrors=True))
  100. yield self.store.set_appservice_last_pos(upper_bound)
  101. now = self.clock.time_msec()
  102. ts = yield self.store.get_received_ts(events[-1].event_id)
  103. synapse.metrics.event_processing_positions.labels(
  104. "appservice_sender").set(upper_bound)
  105. events_processed_counter.inc(len(events))
  106. event_processing_loop_room_count.labels(
  107. "appservice_sender"
  108. ).inc(len(events_by_room))
  109. event_processing_loop_counter.labels("appservice_sender").inc()
  110. synapse.metrics.event_processing_lag.labels(
  111. "appservice_sender").set(now - ts)
  112. synapse.metrics.event_processing_last_ts.labels(
  113. "appservice_sender").set(ts)
  114. finally:
  115. self.is_processing = False
  116. @defer.inlineCallbacks
  117. def query_user_exists(self, user_id):
  118. """Check if any application service knows this user_id exists.
  119. Args:
  120. user_id(str): The user to query if they exist on any AS.
  121. Returns:
  122. True if this user exists on at least one application service.
  123. """
  124. user_query_services = yield self._get_services_for_user(
  125. user_id=user_id
  126. )
  127. for user_service in user_query_services:
  128. is_known_user = yield self.appservice_api.query_user(
  129. user_service, user_id
  130. )
  131. if is_known_user:
  132. defer.returnValue(True)
  133. defer.returnValue(False)
  134. @defer.inlineCallbacks
  135. def query_room_alias_exists(self, room_alias):
  136. """Check if an application service knows this room alias exists.
  137. Args:
  138. room_alias(RoomAlias): The room alias to query.
  139. Returns:
  140. namedtuple: with keys "room_id" and "servers" or None if no
  141. association can be found.
  142. """
  143. room_alias_str = room_alias.to_string()
  144. services = self.store.get_app_services()
  145. alias_query_services = [
  146. s for s in services if (
  147. s.is_interested_in_alias(room_alias_str)
  148. )
  149. ]
  150. for alias_service in alias_query_services:
  151. is_known_alias = yield self.appservice_api.query_alias(
  152. alias_service, room_alias_str
  153. )
  154. if is_known_alias:
  155. # the alias exists now so don't query more ASes.
  156. result = yield self.store.get_association_from_room_alias(
  157. room_alias
  158. )
  159. defer.returnValue(result)
  160. @defer.inlineCallbacks
  161. def query_3pe(self, kind, protocol, fields):
  162. services = yield self._get_services_for_3pn(protocol)
  163. results = yield make_deferred_yieldable(defer.DeferredList([
  164. run_in_background(
  165. self.appservice_api.query_3pe,
  166. service, kind, protocol, fields,
  167. )
  168. for service in services
  169. ], consumeErrors=True))
  170. ret = []
  171. for (success, result) in results:
  172. if success:
  173. ret.extend(result)
  174. defer.returnValue(ret)
  175. @defer.inlineCallbacks
  176. def get_3pe_protocols(self, only_protocol=None):
  177. services = self.store.get_app_services()
  178. protocols = {}
  179. # Collect up all the individual protocol responses out of the ASes
  180. for s in services:
  181. for p in s.protocols:
  182. if only_protocol is not None and p != only_protocol:
  183. continue
  184. if p not in protocols:
  185. protocols[p] = []
  186. info = yield self.appservice_api.get_3pe_protocol(s, p)
  187. if info is not None:
  188. protocols[p].append(info)
  189. def _merge_instances(infos):
  190. if not infos:
  191. return {}
  192. # Merge the 'instances' lists of multiple results, but just take
  193. # the other fields from the first as they ought to be identical
  194. # copy the result so as not to corrupt the cached one
  195. combined = dict(infos[0])
  196. combined["instances"] = list(combined["instances"])
  197. for info in infos[1:]:
  198. combined["instances"].extend(info["instances"])
  199. return combined
  200. for p in protocols.keys():
  201. protocols[p] = _merge_instances(protocols[p])
  202. defer.returnValue(protocols)
  203. @defer.inlineCallbacks
  204. def _get_services_for_event(self, event):
  205. """Retrieve a list of application services interested in this event.
  206. Args:
  207. event(Event): The event to check. Can be None if alias_list is not.
  208. Returns:
  209. list<ApplicationService>: A list of services interested in this
  210. event based on the service regex.
  211. """
  212. services = self.store.get_app_services()
  213. # we can't use a list comprehension here. Since python 3, list
  214. # comprehensions use a generator internally. This means you can't yield
  215. # inside of a list comprehension anymore.
  216. interested_list = []
  217. for s in services:
  218. if (yield s.is_interested(event, self.store)):
  219. interested_list.append(s)
  220. defer.returnValue(interested_list)
  221. def _get_services_for_user(self, user_id):
  222. services = self.store.get_app_services()
  223. interested_list = [
  224. s for s in services if (
  225. s.is_interested_in_user(user_id)
  226. )
  227. ]
  228. return defer.succeed(interested_list)
  229. def _get_services_for_3pn(self, protocol):
  230. services = self.store.get_app_services()
  231. interested_list = [
  232. s for s in services if s.is_interested_in_protocol(protocol)
  233. ]
  234. return defer.succeed(interested_list)
  235. @defer.inlineCallbacks
  236. def _is_unknown_user(self, user_id):
  237. if not self.is_mine_id(user_id):
  238. # we don't know if they are unknown or not since it isn't one of our
  239. # users. We can't poke ASes.
  240. defer.returnValue(False)
  241. return
  242. user_info = yield self.store.get_user_by_id(user_id)
  243. if user_info:
  244. defer.returnValue(False)
  245. return
  246. # user not found; could be the AS though, so check.
  247. services = self.store.get_app_services()
  248. service_list = [s for s in services if s.sender == user_id]
  249. defer.returnValue(len(service_list) == 0)
  250. @defer.inlineCallbacks
  251. def _check_user_exists(self, user_id):
  252. unknown_user = yield self._is_unknown_user(user_id)
  253. if unknown_user:
  254. exists = yield self.query_user_exists(user_id)
  255. defer.returnValue(exists)
  256. defer.returnValue(True)