appservice.py 11 KB

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