synchrotron.py 17 KB

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