synchrotron.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 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 contextlib
  17. import logging
  18. import sys
  19. from six import iteritems
  20. from twisted.internet import defer, reactor
  21. from twisted.web.resource import NoResource
  22. import synapse
  23. from synapse.api.constants import EventTypes
  24. from synapse.app import _base
  25. from synapse.config._base import ConfigError
  26. from synapse.config.homeserver import HomeServerConfig
  27. from synapse.config.logger import setup_logging
  28. from synapse.handlers.presence import PresenceHandler, get_interested_parties
  29. from synapse.http.server import JsonResource
  30. from synapse.http.site import SynapseSite
  31. from synapse.metrics import RegistryProxy
  32. from synapse.metrics.resource import METRICS_PREFIX, MetricsResource
  33. from synapse.replication.slave.storage._base import BaseSlavedStore, __func__
  34. from synapse.replication.slave.storage.account_data import SlavedAccountDataStore
  35. from synapse.replication.slave.storage.appservice import SlavedApplicationServiceStore
  36. from synapse.replication.slave.storage.client_ips import SlavedClientIpStore
  37. from synapse.replication.slave.storage.deviceinbox import SlavedDeviceInboxStore
  38. from synapse.replication.slave.storage.devices import SlavedDeviceStore
  39. from synapse.replication.slave.storage.events import SlavedEventStore
  40. from synapse.replication.slave.storage.filtering import SlavedFilteringStore
  41. from synapse.replication.slave.storage.groups import SlavedGroupServerStore
  42. from synapse.replication.slave.storage.presence import SlavedPresenceStore
  43. from synapse.replication.slave.storage.push_rule import SlavedPushRuleStore
  44. from synapse.replication.slave.storage.receipts import SlavedReceiptsStore
  45. from synapse.replication.slave.storage.registration import SlavedRegistrationStore
  46. from synapse.replication.slave.storage.room import RoomStore
  47. from synapse.replication.tcp.client import ReplicationClientHandler
  48. from synapse.rest.client.v1 import events
  49. from synapse.rest.client.v1.initial_sync import InitialSyncRestServlet
  50. from synapse.rest.client.v1.room import RoomInitialSyncRestServlet
  51. from synapse.rest.client.v2_alpha import sync
  52. from synapse.server import HomeServer
  53. from synapse.storage.engines import create_engine
  54. from synapse.storage.presence import UserPresenceState
  55. from synapse.util.httpresourcetree import create_resource_tree
  56. from synapse.util.logcontext import LoggingContext, run_in_background
  57. from synapse.util.manhole import manhole
  58. from synapse.util.stringutils import random_string
  59. from synapse.util.versionstring import get_version_string
  60. logger = logging.getLogger("synapse.app.synchrotron")
  61. class SynchrotronSlavedStore(
  62. SlavedReceiptsStore,
  63. SlavedAccountDataStore,
  64. SlavedApplicationServiceStore,
  65. SlavedRegistrationStore,
  66. SlavedFilteringStore,
  67. SlavedPresenceStore,
  68. SlavedGroupServerStore,
  69. SlavedDeviceInboxStore,
  70. SlavedDeviceStore,
  71. SlavedPushRuleStore,
  72. SlavedEventStore,
  73. SlavedClientIpStore,
  74. RoomStore,
  75. BaseSlavedStore,
  76. ):
  77. pass
  78. UPDATE_SYNCING_USERS_MS = 10 * 1000
  79. class SynchrotronPresence(object):
  80. def __init__(self, hs):
  81. self.hs = hs
  82. self.is_mine_id = hs.is_mine_id
  83. self.http_client = hs.get_simple_http_client()
  84. self.store = hs.get_datastore()
  85. self.user_to_num_current_syncs = {}
  86. self.clock = hs.get_clock()
  87. self.notifier = hs.get_notifier()
  88. active_presence = self.store.take_presence_startup_info()
  89. self.user_to_current_state = {
  90. state.user_id: state
  91. for state in active_presence
  92. }
  93. # user_id -> last_sync_ms. Lists the users that have stopped syncing
  94. # but we haven't notified the master of that yet
  95. self.users_going_offline = {}
  96. self._send_stop_syncing_loop = self.clock.looping_call(
  97. self.send_stop_syncing, 10 * 1000
  98. )
  99. self.process_id = random_string(16)
  100. logger.info("Presence process_id is %r", self.process_id)
  101. def send_user_sync(self, user_id, is_syncing, last_sync_ms):
  102. if self.hs.config.use_presence:
  103. self.hs.get_tcp_replication().send_user_sync(
  104. user_id, is_syncing, last_sync_ms
  105. )
  106. def mark_as_coming_online(self, user_id):
  107. """A user has started syncing. Send a UserSync to the master, unless they
  108. had recently stopped syncing.
  109. Args:
  110. user_id (str)
  111. """
  112. going_offline = self.users_going_offline.pop(user_id, None)
  113. if not going_offline:
  114. # Safe to skip because we haven't yet told the master they were offline
  115. self.send_user_sync(user_id, True, self.clock.time_msec())
  116. def mark_as_going_offline(self, user_id):
  117. """A user has stopped syncing. We wait before notifying the master as
  118. its likely they'll come back soon. This allows us to avoid sending
  119. a stopped syncing immediately followed by a started syncing notification
  120. to the master
  121. Args:
  122. user_id (str)
  123. """
  124. self.users_going_offline[user_id] = self.clock.time_msec()
  125. def send_stop_syncing(self):
  126. """Check if there are any users who have stopped syncing a while ago
  127. and haven't come back yet. If there are poke the master about them.
  128. """
  129. now = self.clock.time_msec()
  130. for user_id, last_sync_ms in list(self.users_going_offline.items()):
  131. if now - last_sync_ms > 10 * 1000:
  132. self.users_going_offline.pop(user_id, None)
  133. self.send_user_sync(user_id, False, last_sync_ms)
  134. def set_state(self, user, state, ignore_status_msg=False):
  135. # TODO Hows this supposed to work?
  136. pass
  137. get_states = __func__(PresenceHandler.get_states)
  138. get_state = __func__(PresenceHandler.get_state)
  139. current_state_for_users = __func__(PresenceHandler.current_state_for_users)
  140. def user_syncing(self, user_id, affect_presence):
  141. if affect_presence:
  142. curr_sync = self.user_to_num_current_syncs.get(user_id, 0)
  143. self.user_to_num_current_syncs[user_id] = curr_sync + 1
  144. # If we went from no in flight sync to some, notify replication
  145. if self.user_to_num_current_syncs[user_id] == 1:
  146. self.mark_as_coming_online(user_id)
  147. def _end():
  148. # We check that the user_id is in user_to_num_current_syncs because
  149. # user_to_num_current_syncs may have been cleared if we are
  150. # shutting down.
  151. if affect_presence and user_id in self.user_to_num_current_syncs:
  152. self.user_to_num_current_syncs[user_id] -= 1
  153. # If we went from one in flight sync to non, notify replication
  154. if self.user_to_num_current_syncs[user_id] == 0:
  155. self.mark_as_going_offline(user_id)
  156. @contextlib.contextmanager
  157. def _user_syncing():
  158. try:
  159. yield
  160. finally:
  161. _end()
  162. return defer.succeed(_user_syncing())
  163. @defer.inlineCallbacks
  164. def notify_from_replication(self, states, stream_id):
  165. parties = yield get_interested_parties(self.store, states)
  166. room_ids_to_states, users_to_states = parties
  167. self.notifier.on_new_event(
  168. "presence_key", stream_id, rooms=room_ids_to_states.keys(),
  169. users=users_to_states.keys()
  170. )
  171. @defer.inlineCallbacks
  172. def process_replication_rows(self, token, rows):
  173. states = [UserPresenceState(
  174. row.user_id, row.state, row.last_active_ts,
  175. row.last_federation_update_ts, row.last_user_sync_ts, row.status_msg,
  176. row.currently_active
  177. ) for row in rows]
  178. for state in states:
  179. self.user_to_current_state[state.user_id] = state
  180. stream_id = token
  181. yield self.notify_from_replication(states, stream_id)
  182. def get_currently_syncing_users(self):
  183. if self.hs.config.use_presence:
  184. return [
  185. user_id for user_id, count in iteritems(self.user_to_num_current_syncs)
  186. if count > 0
  187. ]
  188. else:
  189. return set()
  190. class SynchrotronTyping(object):
  191. def __init__(self, hs):
  192. self._latest_room_serial = 0
  193. self._room_serials = {}
  194. self._room_typing = {}
  195. def stream_positions(self):
  196. # We must update this typing token from the response of the previous
  197. # sync. In particular, the stream id may "reset" back to zero/a low
  198. # value which we *must* use for the next replication request.
  199. return {"typing": self._latest_room_serial}
  200. def process_replication_rows(self, token, rows):
  201. self._latest_room_serial = token
  202. for row in rows:
  203. self._room_serials[row.room_id] = token
  204. self._room_typing[row.room_id] = row.user_ids
  205. class SynchrotronApplicationService(object):
  206. def notify_interested_services(self, event):
  207. pass
  208. class SynchrotronServer(HomeServer):
  209. DATASTORE_CLASS = SynchrotronSlavedStore
  210. def _listen_http(self, listener_config):
  211. port = listener_config["port"]
  212. bind_addresses = listener_config["bind_addresses"]
  213. site_tag = listener_config.get("tag", port)
  214. resources = {}
  215. for res in listener_config["resources"]:
  216. for name in res["names"]:
  217. if name == "metrics":
  218. resources[METRICS_PREFIX] = MetricsResource(RegistryProxy)
  219. elif name == "client":
  220. resource = JsonResource(self, canonical_json=False)
  221. sync.register_servlets(self, resource)
  222. events.register_servlets(self, resource)
  223. InitialSyncRestServlet(self).register(resource)
  224. RoomInitialSyncRestServlet(self).register(resource)
  225. resources.update({
  226. "/_matrix/client/r0": resource,
  227. "/_matrix/client/unstable": resource,
  228. "/_matrix/client/v2_alpha": resource,
  229. "/_matrix/client/api/v1": resource,
  230. })
  231. root_resource = create_resource_tree(resources, NoResource())
  232. _base.listen_tcp(
  233. bind_addresses,
  234. port,
  235. SynapseSite(
  236. "synapse.access.http.%s" % (site_tag,),
  237. site_tag,
  238. listener_config,
  239. root_resource,
  240. self.version_string,
  241. )
  242. )
  243. logger.info("Synapse synchrotron now listening on port %d", port)
  244. def start_listening(self, listeners):
  245. for listener in listeners:
  246. if listener["type"] == "http":
  247. self._listen_http(listener)
  248. elif listener["type"] == "manhole":
  249. _base.listen_tcp(
  250. listener["bind_addresses"],
  251. listener["port"],
  252. manhole(
  253. username="matrix",
  254. password="rabbithole",
  255. globals={"hs": self},
  256. )
  257. )
  258. elif listener["type"] == "metrics":
  259. if not self.get_config().enable_metrics:
  260. logger.warn(("Metrics listener configured, but "
  261. "enable_metrics is not True!"))
  262. else:
  263. _base.listen_metrics(listener["bind_addresses"],
  264. listener["port"])
  265. else:
  266. logger.warn("Unrecognized listener type: %s", listener["type"])
  267. self.get_tcp_replication().start_replication(self)
  268. def build_tcp_replication(self):
  269. return SyncReplicationHandler(self)
  270. def build_presence_handler(self):
  271. return SynchrotronPresence(self)
  272. def build_typing_handler(self):
  273. return SynchrotronTyping(self)
  274. class SyncReplicationHandler(ReplicationClientHandler):
  275. def __init__(self, hs):
  276. super(SyncReplicationHandler, self).__init__(hs.get_datastore())
  277. self.store = hs.get_datastore()
  278. self.typing_handler = hs.get_typing_handler()
  279. # NB this is a SynchrotronPresence, not a normal PresenceHandler
  280. self.presence_handler = hs.get_presence_handler()
  281. self.notifier = hs.get_notifier()
  282. @defer.inlineCallbacks
  283. def on_rdata(self, stream_name, token, rows):
  284. yield super(SyncReplicationHandler, self).on_rdata(stream_name, token, rows)
  285. run_in_background(self.process_and_notify, stream_name, token, rows)
  286. def get_streams_to_replicate(self):
  287. args = super(SyncReplicationHandler, self).get_streams_to_replicate()
  288. args.update(self.typing_handler.stream_positions())
  289. return args
  290. def get_currently_syncing_users(self):
  291. return self.presence_handler.get_currently_syncing_users()
  292. @defer.inlineCallbacks
  293. def process_and_notify(self, stream_name, token, rows):
  294. try:
  295. if stream_name == "events":
  296. # We shouldn't get multiple rows per token for events stream, so
  297. # we don't need to optimise this for multiple rows.
  298. for row in rows:
  299. event = yield self.store.get_event(row.event_id)
  300. extra_users = ()
  301. if event.type == EventTypes.Member:
  302. extra_users = (event.state_key,)
  303. max_token = self.store.get_room_max_stream_ordering()
  304. self.notifier.on_new_room_event(
  305. event, token, max_token, extra_users
  306. )
  307. elif stream_name == "push_rules":
  308. self.notifier.on_new_event(
  309. "push_rules_key", token, users=[row.user_id for row in rows],
  310. )
  311. elif stream_name in ("account_data", "tag_account_data",):
  312. self.notifier.on_new_event(
  313. "account_data_key", token, users=[row.user_id for row in rows],
  314. )
  315. elif stream_name == "receipts":
  316. self.notifier.on_new_event(
  317. "receipt_key", token, rooms=[row.room_id for row in rows],
  318. )
  319. elif stream_name == "typing":
  320. self.typing_handler.process_replication_rows(token, rows)
  321. self.notifier.on_new_event(
  322. "typing_key", token, rooms=[row.room_id for row in rows],
  323. )
  324. elif stream_name == "to_device":
  325. entities = [row.entity for row in rows if row.entity.startswith("@")]
  326. if entities:
  327. self.notifier.on_new_event(
  328. "to_device_key", token, users=entities,
  329. )
  330. elif stream_name == "device_lists":
  331. all_room_ids = set()
  332. for row in rows:
  333. room_ids = yield self.store.get_rooms_for_user(row.user_id)
  334. all_room_ids.update(room_ids)
  335. self.notifier.on_new_event(
  336. "device_list_key", token, rooms=all_room_ids,
  337. )
  338. elif stream_name == "presence":
  339. yield self.presence_handler.process_replication_rows(token, rows)
  340. elif stream_name == "receipts":
  341. self.notifier.on_new_event(
  342. "groups_key", token, users=[row.user_id for row in rows],
  343. )
  344. except Exception:
  345. logger.exception("Error processing replication")
  346. def start(config_options):
  347. try:
  348. config = HomeServerConfig.load_config(
  349. "Synapse synchrotron", config_options
  350. )
  351. except ConfigError as e:
  352. sys.stderr.write("\n" + str(e) + "\n")
  353. sys.exit(1)
  354. assert config.worker_app == "synapse.app.synchrotron"
  355. setup_logging(config, use_worker_options=True)
  356. synapse.events.USE_FROZEN_DICTS = config.use_frozen_dicts
  357. database_engine = create_engine(config.database_config)
  358. ss = SynchrotronServer(
  359. config.server_name,
  360. db_config=config.database_config,
  361. config=config,
  362. version_string="Synapse/" + get_version_string(synapse),
  363. database_engine=database_engine,
  364. application_service_handler=SynchrotronApplicationService(),
  365. )
  366. ss.setup()
  367. ss.start_listening(config.worker_listeners)
  368. def start():
  369. ss.get_datastore().start_profiling()
  370. reactor.callWhenRunning(start)
  371. _base.start_worker_reactor("synapse-synchrotron", config)
  372. if __name__ == '__main__':
  373. with LoggingContext("main"):
  374. start(sys.argv[1:])