synchrotron.py 16 KB

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