synchrotron.py 16 KB

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