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
  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.storage.roommember import RoomMemberStore
  56. from synapse.util.httpresourcetree import create_resource_tree
  57. from synapse.util.logcontext import LoggingContext, run_in_background
  58. from synapse.util.manhole import manhole
  59. from synapse.util.stringutils import random_string
  60. from synapse.util.versionstring import get_version_string
  61. logger = logging.getLogger("synapse.app.synchrotron")
  62. class SynchrotronSlavedStore(
  63. SlavedReceiptsStore,
  64. SlavedAccountDataStore,
  65. SlavedApplicationServiceStore,
  66. SlavedRegistrationStore,
  67. SlavedFilteringStore,
  68. SlavedPresenceStore,
  69. SlavedGroupServerStore,
  70. SlavedDeviceInboxStore,
  71. SlavedDeviceStore,
  72. SlavedPushRuleStore,
  73. SlavedEventStore,
  74. SlavedClientIpStore,
  75. RoomStore,
  76. BaseSlavedStore,
  77. ):
  78. did_forget = (
  79. RoomMemberStore.__dict__["did_forget"]
  80. )
  81. UPDATE_SYNCING_USERS_MS = 10 * 1000
  82. class SynchrotronPresence(object):
  83. def __init__(self, hs):
  84. self.hs = hs
  85. self.is_mine_id = hs.is_mine_id
  86. self.http_client = hs.get_simple_http_client()
  87. self.store = hs.get_datastore()
  88. self.user_to_num_current_syncs = {}
  89. self.clock = hs.get_clock()
  90. self.notifier = hs.get_notifier()
  91. active_presence = self.store.take_presence_startup_info()
  92. self.user_to_current_state = {
  93. state.user_id: state
  94. for state in active_presence
  95. }
  96. # user_id -> last_sync_ms. Lists the users that have stopped syncing
  97. # but we haven't notified the master of that yet
  98. self.users_going_offline = {}
  99. self._send_stop_syncing_loop = self.clock.looping_call(
  100. self.send_stop_syncing, 10 * 1000
  101. )
  102. self.process_id = random_string(16)
  103. logger.info("Presence process_id is %r", self.process_id)
  104. def send_user_sync(self, user_id, is_syncing, last_sync_ms):
  105. self.hs.get_tcp_replication().send_user_sync(user_id, is_syncing, last_sync_ms)
  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 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 = PresenceHandler.get_states.__func__
  138. get_state = PresenceHandler.get_state.__func__
  139. current_state_for_users = PresenceHandler.current_state_for_users.__func__
  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[row.user_id] = state
  180. stream_id = token
  181. yield self.notify_from_replication(states, stream_id)
  182. def get_currently_syncing_users(self):
  183. return [
  184. user_id for user_id, count in iteritems(self.user_to_num_current_syncs)
  185. if count > 0
  186. ]
  187. class SynchrotronTyping(object):
  188. def __init__(self, hs):
  189. self._latest_room_serial = 0
  190. self._room_serials = {}
  191. self._room_typing = {}
  192. def stream_positions(self):
  193. # We must update this typing token from the response of the previous
  194. # sync. In particular, the stream id may "reset" back to zero/a low
  195. # value which we *must* use for the next replication request.
  196. return {"typing": self._latest_room_serial}
  197. def process_replication_rows(self, token, rows):
  198. self._latest_room_serial = token
  199. for row in rows:
  200. self._room_serials[row.room_id] = token
  201. self._room_typing[row.room_id] = row.user_ids
  202. class SynchrotronApplicationService(object):
  203. def notify_interested_services(self, event):
  204. pass
  205. class SynchrotronServer(HomeServer):
  206. def setup(self):
  207. logger.info("Setting up.")
  208. self.datastore = SynchrotronSlavedStore(self.get_db_conn(), self)
  209. logger.info("Finished setting up.")
  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. def on_rdata(self, stream_name, token, rows):
  283. super(SyncReplicationHandler, self).on_rdata(stream_name, token, rows)
  284. run_in_background(self.process_and_notify, stream_name, token, rows)
  285. def get_streams_to_replicate(self):
  286. args = super(SyncReplicationHandler, self).get_streams_to_replicate()
  287. args.update(self.typing_handler.stream_positions())
  288. return args
  289. def get_currently_syncing_users(self):
  290. return self.presence_handler.get_currently_syncing_users()
  291. @defer.inlineCallbacks
  292. def process_and_notify(self, stream_name, token, rows):
  293. try:
  294. if stream_name == "events":
  295. # We shouldn't get multiple rows per token for events stream, so
  296. # we don't need to optimise this for multiple rows.
  297. for row in rows:
  298. event = yield self.store.get_event(row.event_id)
  299. extra_users = ()
  300. if event.type == EventTypes.Member:
  301. extra_users = (event.state_key,)
  302. max_token = self.store.get_room_max_stream_ordering()
  303. self.notifier.on_new_room_event(
  304. event, token, max_token, extra_users
  305. )
  306. elif stream_name == "push_rules":
  307. self.notifier.on_new_event(
  308. "push_rules_key", token, users=[row.user_id for row in rows],
  309. )
  310. elif stream_name in ("account_data", "tag_account_data",):
  311. self.notifier.on_new_event(
  312. "account_data_key", token, users=[row.user_id for row in rows],
  313. )
  314. elif stream_name == "receipts":
  315. self.notifier.on_new_event(
  316. "receipt_key", token, rooms=[row.room_id for row in rows],
  317. )
  318. elif stream_name == "typing":
  319. self.typing_handler.process_replication_rows(token, rows)
  320. self.notifier.on_new_event(
  321. "typing_key", token, rooms=[row.room_id for row in rows],
  322. )
  323. elif stream_name == "to_device":
  324. entities = [row.entity for row in rows if row.entity.startswith("@")]
  325. if entities:
  326. self.notifier.on_new_event(
  327. "to_device_key", token, users=entities,
  328. )
  329. elif stream_name == "device_lists":
  330. all_room_ids = set()
  331. for row in rows:
  332. room_ids = yield self.store.get_rooms_for_user(row.user_id)
  333. all_room_ids.update(room_ids)
  334. self.notifier.on_new_event(
  335. "device_list_key", token, rooms=all_room_ids,
  336. )
  337. elif stream_name == "presence":
  338. yield self.presence_handler.process_replication_rows(token, rows)
  339. elif stream_name == "receipts":
  340. self.notifier.on_new_event(
  341. "groups_key", token, users=[row.user_id for row in rows],
  342. )
  343. except Exception:
  344. logger.exception("Error processing replication")
  345. def start(config_options):
  346. try:
  347. config = HomeServerConfig.load_config(
  348. "Synapse synchrotron", config_options
  349. )
  350. except ConfigError as e:
  351. sys.stderr.write("\n" + e.message + "\n")
  352. sys.exit(1)
  353. assert config.worker_app == "synapse.app.synchrotron"
  354. setup_logging(config, use_worker_options=True)
  355. synapse.events.USE_FROZEN_DICTS = config.use_frozen_dicts
  356. database_engine = create_engine(config.database_config)
  357. ss = SynchrotronServer(
  358. config.server_name,
  359. db_config=config.database_config,
  360. config=config,
  361. version_string="Synapse/" + get_version_string(synapse),
  362. database_engine=database_engine,
  363. application_service_handler=SynchrotronApplicationService(),
  364. )
  365. ss.setup()
  366. ss.start_listening(config.worker_listeners)
  367. def start():
  368. ss.get_datastore().start_profiling()
  369. ss.get_state_handler().start_caching()
  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:])