generic_worker.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2016 OpenMarket Ltd
  4. # Copyright 2020 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import contextlib
  18. import logging
  19. import sys
  20. from typing import Dict, Iterable, Optional, Set
  21. from typing_extensions import ContextManager
  22. from twisted.internet import defer, reactor
  23. import synapse
  24. import synapse.events
  25. from synapse.api.errors import HttpResponseException, RequestSendFailed, SynapseError
  26. from synapse.api.urls import (
  27. CLIENT_API_PREFIX,
  28. FEDERATION_PREFIX,
  29. LEGACY_MEDIA_PREFIX,
  30. MEDIA_PREFIX,
  31. SERVER_KEY_V2_PREFIX,
  32. )
  33. from synapse.app import _base
  34. from synapse.config._base import ConfigError
  35. from synapse.config.homeserver import HomeServerConfig
  36. from synapse.config.logger import setup_logging
  37. from synapse.federation import send_queue
  38. from synapse.federation.transport.server import TransportLayerServer
  39. from synapse.handlers.presence import (
  40. BasePresenceHandler,
  41. PresenceState,
  42. get_interested_parties,
  43. )
  44. from synapse.http.server import JsonResource, OptionsResource
  45. from synapse.http.servlet import RestServlet, parse_json_object_from_request
  46. from synapse.http.site import SynapseSite
  47. from synapse.logging.context import LoggingContext
  48. from synapse.metrics import METRICS_PREFIX, MetricsResource, RegistryProxy
  49. from synapse.metrics.background_process_metrics import run_as_background_process
  50. from synapse.replication.http import REPLICATION_PREFIX, ReplicationRestResource
  51. from synapse.replication.http.presence import (
  52. ReplicationBumpPresenceActiveTime,
  53. ReplicationPresenceSetState,
  54. )
  55. from synapse.replication.slave.storage._base import BaseSlavedStore
  56. from synapse.replication.slave.storage.account_data import SlavedAccountDataStore
  57. from synapse.replication.slave.storage.appservice import SlavedApplicationServiceStore
  58. from synapse.replication.slave.storage.client_ips import SlavedClientIpStore
  59. from synapse.replication.slave.storage.deviceinbox import SlavedDeviceInboxStore
  60. from synapse.replication.slave.storage.devices import SlavedDeviceStore
  61. from synapse.replication.slave.storage.directory import DirectoryStore
  62. from synapse.replication.slave.storage.events import SlavedEventStore
  63. from synapse.replication.slave.storage.filtering import SlavedFilteringStore
  64. from synapse.replication.slave.storage.groups import SlavedGroupServerStore
  65. from synapse.replication.slave.storage.keys import SlavedKeyStore
  66. from synapse.replication.slave.storage.presence import SlavedPresenceStore
  67. from synapse.replication.slave.storage.profile import SlavedProfileStore
  68. from synapse.replication.slave.storage.push_rule import SlavedPushRuleStore
  69. from synapse.replication.slave.storage.pushers import SlavedPusherStore
  70. from synapse.replication.slave.storage.receipts import SlavedReceiptsStore
  71. from synapse.replication.slave.storage.registration import SlavedRegistrationStore
  72. from synapse.replication.slave.storage.room import RoomStore
  73. from synapse.replication.slave.storage.transactions import SlavedTransactionStore
  74. from synapse.replication.tcp.client import ReplicationDataHandler
  75. from synapse.replication.tcp.commands import ClearUserSyncsCommand
  76. from synapse.replication.tcp.streams import (
  77. AccountDataStream,
  78. DeviceListsStream,
  79. GroupServerStream,
  80. PresenceStream,
  81. PushersStream,
  82. PushRulesStream,
  83. ReceiptsStream,
  84. TagAccountDataStream,
  85. ToDeviceStream,
  86. TypingStream,
  87. )
  88. from synapse.rest.admin import register_servlets_for_media_repo
  89. from synapse.rest.client.v1 import events
  90. from synapse.rest.client.v1.initial_sync import InitialSyncRestServlet
  91. from synapse.rest.client.v1.login import LoginRestServlet
  92. from synapse.rest.client.v1.profile import (
  93. ProfileAvatarURLRestServlet,
  94. ProfileDisplaynameRestServlet,
  95. ProfileRestServlet,
  96. )
  97. from synapse.rest.client.v1.push_rule import PushRuleRestServlet
  98. from synapse.rest.client.v1.room import (
  99. JoinedRoomMemberListRestServlet,
  100. JoinRoomAliasServlet,
  101. PublicRoomListRestServlet,
  102. RoomEventContextServlet,
  103. RoomInitialSyncRestServlet,
  104. RoomMemberListRestServlet,
  105. RoomMembershipRestServlet,
  106. RoomMessageListRestServlet,
  107. RoomSendEventRestServlet,
  108. RoomStateEventRestServlet,
  109. RoomStateRestServlet,
  110. )
  111. from synapse.rest.client.v1.voip import VoipRestServlet
  112. from synapse.rest.client.v2_alpha import groups, sync, user_directory
  113. from synapse.rest.client.v2_alpha._base import client_patterns
  114. from synapse.rest.client.v2_alpha.account import ThreepidRestServlet
  115. from synapse.rest.client.v2_alpha.account_data import (
  116. AccountDataServlet,
  117. RoomAccountDataServlet,
  118. )
  119. from synapse.rest.client.v2_alpha.keys import KeyChangesServlet, KeyQueryServlet
  120. from synapse.rest.client.v2_alpha.register import RegisterRestServlet
  121. from synapse.rest.client.versions import VersionsRestServlet
  122. from synapse.rest.key.v2 import KeyApiV2Resource
  123. from synapse.server import HomeServer
  124. from synapse.storage.data_stores.main.censor_events import CensorEventsStore
  125. from synapse.storage.data_stores.main.media_repository import MediaRepositoryStore
  126. from synapse.storage.data_stores.main.monthly_active_users import (
  127. MonthlyActiveUsersWorkerStore,
  128. )
  129. from synapse.storage.data_stores.main.presence import UserPresenceState
  130. from synapse.storage.data_stores.main.search import SearchWorkerStore
  131. from synapse.storage.data_stores.main.ui_auth import UIAuthWorkerStore
  132. from synapse.storage.data_stores.main.user_directory import UserDirectoryStore
  133. from synapse.types import ReadReceipt
  134. from synapse.util.async_helpers import Linearizer
  135. from synapse.util.httpresourcetree import create_resource_tree
  136. from synapse.util.manhole import manhole
  137. from synapse.util.versionstring import get_version_string
  138. logger = logging.getLogger("synapse.app.generic_worker")
  139. class PresenceStatusStubServlet(RestServlet):
  140. """If presence is disabled this servlet can be used to stub out setting
  141. presence status.
  142. """
  143. PATTERNS = client_patterns("/presence/(?P<user_id>[^/]*)/status")
  144. def __init__(self, hs):
  145. super(PresenceStatusStubServlet, self).__init__()
  146. self.auth = hs.get_auth()
  147. async def on_GET(self, request, user_id):
  148. await self.auth.get_user_by_req(request)
  149. return 200, {"presence": "offline"}
  150. async def on_PUT(self, request, user_id):
  151. await self.auth.get_user_by_req(request)
  152. return 200, {}
  153. class KeyUploadServlet(RestServlet):
  154. """An implementation of the `KeyUploadServlet` that responds to read only
  155. requests, but otherwise proxies through to the master instance.
  156. """
  157. PATTERNS = client_patterns("/keys/upload(/(?P<device_id>[^/]+))?$")
  158. def __init__(self, hs):
  159. """
  160. Args:
  161. hs (synapse.server.HomeServer): server
  162. """
  163. super(KeyUploadServlet, self).__init__()
  164. self.auth = hs.get_auth()
  165. self.store = hs.get_datastore()
  166. self.http_client = hs.get_simple_http_client()
  167. self.main_uri = hs.config.worker_main_http_uri
  168. async def on_POST(self, request, device_id):
  169. requester = await self.auth.get_user_by_req(request, allow_guest=True)
  170. user_id = requester.user.to_string()
  171. body = parse_json_object_from_request(request)
  172. if device_id is not None:
  173. # passing the device_id here is deprecated; however, we allow it
  174. # for now for compatibility with older clients.
  175. if requester.device_id is not None and device_id != requester.device_id:
  176. logger.warning(
  177. "Client uploading keys for a different device "
  178. "(logged in as %s, uploading for %s)",
  179. requester.device_id,
  180. device_id,
  181. )
  182. else:
  183. device_id = requester.device_id
  184. if device_id is None:
  185. raise SynapseError(
  186. 400, "To upload keys, you must pass device_id when authenticating"
  187. )
  188. if body:
  189. # They're actually trying to upload something, proxy to main synapse.
  190. # Pass through the auth headers, if any, in case the access token
  191. # is there.
  192. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization", [])
  193. headers = {"Authorization": auth_headers}
  194. try:
  195. result = await self.http_client.post_json_get_json(
  196. self.main_uri + request.uri.decode("ascii"), body, headers=headers
  197. )
  198. except HttpResponseException as e:
  199. raise e.to_synapse_error() from e
  200. except RequestSendFailed as e:
  201. raise SynapseError(502, "Failed to talk to master") from e
  202. return 200, result
  203. else:
  204. # Just interested in counts.
  205. result = await self.store.count_e2e_one_time_keys(user_id, device_id)
  206. return 200, {"one_time_key_counts": result}
  207. class _NullContextManager(ContextManager[None]):
  208. """A context manager which does nothing."""
  209. def __exit__(self, exc_type, exc_val, exc_tb):
  210. pass
  211. UPDATE_SYNCING_USERS_MS = 10 * 1000
  212. class GenericWorkerPresence(BasePresenceHandler):
  213. def __init__(self, hs):
  214. super().__init__(hs)
  215. self.hs = hs
  216. self.is_mine_id = hs.is_mine_id
  217. self.http_client = hs.get_simple_http_client()
  218. self._presence_enabled = hs.config.use_presence
  219. # The number of ongoing syncs on this process, by user id.
  220. # Empty if _presence_enabled is false.
  221. self._user_to_num_current_syncs = {} # type: Dict[str, int]
  222. self.notifier = hs.get_notifier()
  223. self.instance_id = hs.get_instance_id()
  224. # user_id -> last_sync_ms. Lists the users that have stopped syncing
  225. # but we haven't notified the master of that yet
  226. self.users_going_offline = {}
  227. self._bump_active_client = ReplicationBumpPresenceActiveTime.make_client(hs)
  228. self._set_state_client = ReplicationPresenceSetState.make_client(hs)
  229. self._send_stop_syncing_loop = self.clock.looping_call(
  230. self.send_stop_syncing, UPDATE_SYNCING_USERS_MS
  231. )
  232. hs.get_reactor().addSystemEventTrigger(
  233. "before",
  234. "shutdown",
  235. run_as_background_process,
  236. "generic_presence.on_shutdown",
  237. self._on_shutdown,
  238. )
  239. def _on_shutdown(self):
  240. if self._presence_enabled:
  241. self.hs.get_tcp_replication().send_command(
  242. ClearUserSyncsCommand(self.instance_id)
  243. )
  244. def send_user_sync(self, user_id, is_syncing, last_sync_ms):
  245. if self._presence_enabled:
  246. self.hs.get_tcp_replication().send_user_sync(
  247. self.instance_id, user_id, is_syncing, last_sync_ms
  248. )
  249. def mark_as_coming_online(self, user_id):
  250. """A user has started syncing. Send a UserSync to the master, unless they
  251. had recently stopped syncing.
  252. Args:
  253. user_id (str)
  254. """
  255. going_offline = self.users_going_offline.pop(user_id, None)
  256. if not going_offline:
  257. # Safe to skip because we haven't yet told the master they were offline
  258. self.send_user_sync(user_id, True, self.clock.time_msec())
  259. def mark_as_going_offline(self, user_id):
  260. """A user has stopped syncing. We wait before notifying the master as
  261. its likely they'll come back soon. This allows us to avoid sending
  262. a stopped syncing immediately followed by a started syncing notification
  263. to the master
  264. Args:
  265. user_id (str)
  266. """
  267. self.users_going_offline[user_id] = self.clock.time_msec()
  268. def send_stop_syncing(self):
  269. """Check if there are any users who have stopped syncing a while ago
  270. and haven't come back yet. If there are poke the master about them.
  271. """
  272. now = self.clock.time_msec()
  273. for user_id, last_sync_ms in list(self.users_going_offline.items()):
  274. if now - last_sync_ms > UPDATE_SYNCING_USERS_MS:
  275. self.users_going_offline.pop(user_id, None)
  276. self.send_user_sync(user_id, False, last_sync_ms)
  277. async def user_syncing(
  278. self, user_id: str, affect_presence: bool
  279. ) -> ContextManager[None]:
  280. """Record that a user is syncing.
  281. Called by the sync and events servlets to record that a user has connected to
  282. this worker and is waiting for some events.
  283. """
  284. if not affect_presence or not self._presence_enabled:
  285. return _NullContextManager()
  286. curr_sync = self._user_to_num_current_syncs.get(user_id, 0)
  287. self._user_to_num_current_syncs[user_id] = curr_sync + 1
  288. # If we went from no in flight sync to some, notify replication
  289. if self._user_to_num_current_syncs[user_id] == 1:
  290. self.mark_as_coming_online(user_id)
  291. def _end():
  292. # We check that the user_id is in user_to_num_current_syncs because
  293. # user_to_num_current_syncs may have been cleared if we are
  294. # shutting down.
  295. if user_id in self._user_to_num_current_syncs:
  296. self._user_to_num_current_syncs[user_id] -= 1
  297. # If we went from one in flight sync to non, notify replication
  298. if self._user_to_num_current_syncs[user_id] == 0:
  299. self.mark_as_going_offline(user_id)
  300. @contextlib.contextmanager
  301. def _user_syncing():
  302. try:
  303. yield
  304. finally:
  305. _end()
  306. return _user_syncing()
  307. @defer.inlineCallbacks
  308. def notify_from_replication(self, states, stream_id):
  309. parties = yield get_interested_parties(self.store, states)
  310. room_ids_to_states, users_to_states = parties
  311. self.notifier.on_new_event(
  312. "presence_key",
  313. stream_id,
  314. rooms=room_ids_to_states.keys(),
  315. users=users_to_states.keys(),
  316. )
  317. @defer.inlineCallbacks
  318. def process_replication_rows(self, token, rows):
  319. states = [
  320. UserPresenceState(
  321. row.user_id,
  322. row.state,
  323. row.last_active_ts,
  324. row.last_federation_update_ts,
  325. row.last_user_sync_ts,
  326. row.status_msg,
  327. row.currently_active,
  328. )
  329. for row in rows
  330. ]
  331. for state in states:
  332. self.user_to_current_state[state.user_id] = state
  333. stream_id = token
  334. yield self.notify_from_replication(states, stream_id)
  335. def get_currently_syncing_users_for_replication(self) -> Iterable[str]:
  336. return [
  337. user_id
  338. for user_id, count in self._user_to_num_current_syncs.items()
  339. if count > 0
  340. ]
  341. async def set_state(self, target_user, state, ignore_status_msg=False):
  342. """Set the presence state of the user.
  343. """
  344. presence = state["presence"]
  345. valid_presence = (
  346. PresenceState.ONLINE,
  347. PresenceState.UNAVAILABLE,
  348. PresenceState.OFFLINE,
  349. )
  350. if presence not in valid_presence:
  351. raise SynapseError(400, "Invalid presence state")
  352. user_id = target_user.to_string()
  353. # If presence is disabled, no-op
  354. if not self.hs.config.use_presence:
  355. return
  356. # Proxy request to master
  357. await self._set_state_client(
  358. user_id=user_id, state=state, ignore_status_msg=ignore_status_msg
  359. )
  360. async def bump_presence_active_time(self, user):
  361. """We've seen the user do something that indicates they're interacting
  362. with the app.
  363. """
  364. # If presence is disabled, no-op
  365. if not self.hs.config.use_presence:
  366. return
  367. # Proxy request to master
  368. user_id = user.to_string()
  369. await self._bump_active_client(user_id=user_id)
  370. class GenericWorkerTyping(object):
  371. def __init__(self, hs):
  372. self._latest_room_serial = 0
  373. self._reset()
  374. def _reset(self):
  375. """
  376. Reset the typing handler's data caches.
  377. """
  378. # map room IDs to serial numbers
  379. self._room_serials = {}
  380. # map room IDs to sets of users currently typing
  381. self._room_typing = {}
  382. def process_replication_rows(self, token, rows):
  383. if self._latest_room_serial > token:
  384. # The master has gone backwards. To prevent inconsistent data, just
  385. # clear everything.
  386. self._reset()
  387. # Set the latest serial token to whatever the server gave us.
  388. self._latest_room_serial = token
  389. for row in rows:
  390. self._room_serials[row.room_id] = token
  391. self._room_typing[row.room_id] = row.user_ids
  392. def get_current_token(self) -> int:
  393. return self._latest_room_serial
  394. class GenericWorkerSlavedStore(
  395. # FIXME(#3714): We need to add UserDirectoryStore as we write directly
  396. # rather than going via the correct worker.
  397. UserDirectoryStore,
  398. UIAuthWorkerStore,
  399. SlavedDeviceInboxStore,
  400. SlavedDeviceStore,
  401. SlavedReceiptsStore,
  402. SlavedPushRuleStore,
  403. SlavedGroupServerStore,
  404. SlavedAccountDataStore,
  405. SlavedPusherStore,
  406. CensorEventsStore,
  407. SlavedEventStore,
  408. SlavedKeyStore,
  409. RoomStore,
  410. DirectoryStore,
  411. SlavedApplicationServiceStore,
  412. SlavedRegistrationStore,
  413. SlavedTransactionStore,
  414. SlavedProfileStore,
  415. SlavedClientIpStore,
  416. SlavedPresenceStore,
  417. SlavedFilteringStore,
  418. MonthlyActiveUsersWorkerStore,
  419. MediaRepositoryStore,
  420. SearchWorkerStore,
  421. BaseSlavedStore,
  422. ):
  423. def __init__(self, database, db_conn, hs):
  424. super(GenericWorkerSlavedStore, self).__init__(database, db_conn, hs)
  425. # We pull out the current federation stream position now so that we
  426. # always have a known value for the federation position in memory so
  427. # that we don't have to bounce via a deferred once when we start the
  428. # replication streams.
  429. self.federation_out_pos_startup = self._get_federation_out_pos(db_conn)
  430. def _get_federation_out_pos(self, db_conn):
  431. sql = "SELECT stream_id FROM federation_stream_position WHERE type = ?"
  432. sql = self.database_engine.convert_param_style(sql)
  433. txn = db_conn.cursor()
  434. txn.execute(sql, ("federation",))
  435. rows = txn.fetchall()
  436. txn.close()
  437. return rows[0][0] if rows else -1
  438. class GenericWorkerServer(HomeServer):
  439. DATASTORE_CLASS = GenericWorkerSlavedStore
  440. def _listen_http(self, listener_config):
  441. port = listener_config["port"]
  442. bind_addresses = listener_config["bind_addresses"]
  443. site_tag = listener_config.get("tag", port)
  444. resources = {}
  445. for res in listener_config["resources"]:
  446. for name in res["names"]:
  447. if name == "metrics":
  448. resources[METRICS_PREFIX] = MetricsResource(RegistryProxy)
  449. elif name == "client":
  450. resource = JsonResource(self, canonical_json=False)
  451. PublicRoomListRestServlet(self).register(resource)
  452. RoomMemberListRestServlet(self).register(resource)
  453. JoinedRoomMemberListRestServlet(self).register(resource)
  454. RoomStateRestServlet(self).register(resource)
  455. RoomEventContextServlet(self).register(resource)
  456. RoomMessageListRestServlet(self).register(resource)
  457. RegisterRestServlet(self).register(resource)
  458. LoginRestServlet(self).register(resource)
  459. ThreepidRestServlet(self).register(resource)
  460. KeyQueryServlet(self).register(resource)
  461. KeyChangesServlet(self).register(resource)
  462. VoipRestServlet(self).register(resource)
  463. PushRuleRestServlet(self).register(resource)
  464. VersionsRestServlet(self).register(resource)
  465. RoomSendEventRestServlet(self).register(resource)
  466. RoomMembershipRestServlet(self).register(resource)
  467. RoomStateEventRestServlet(self).register(resource)
  468. JoinRoomAliasServlet(self).register(resource)
  469. ProfileAvatarURLRestServlet(self).register(resource)
  470. ProfileDisplaynameRestServlet(self).register(resource)
  471. ProfileRestServlet(self).register(resource)
  472. KeyUploadServlet(self).register(resource)
  473. AccountDataServlet(self).register(resource)
  474. RoomAccountDataServlet(self).register(resource)
  475. sync.register_servlets(self, resource)
  476. events.register_servlets(self, resource)
  477. InitialSyncRestServlet(self).register(resource)
  478. RoomInitialSyncRestServlet(self).register(resource)
  479. user_directory.register_servlets(self, resource)
  480. # If presence is disabled, use the stub servlet that does
  481. # not allow sending presence
  482. if not self.config.use_presence:
  483. PresenceStatusStubServlet(self).register(resource)
  484. groups.register_servlets(self, resource)
  485. resources.update({CLIENT_API_PREFIX: resource})
  486. elif name == "federation":
  487. resources.update({FEDERATION_PREFIX: TransportLayerServer(self)})
  488. elif name == "media":
  489. if self.config.can_load_media_repo:
  490. media_repo = self.get_media_repository_resource()
  491. # We need to serve the admin servlets for media on the
  492. # worker.
  493. admin_resource = JsonResource(self, canonical_json=False)
  494. register_servlets_for_media_repo(self, admin_resource)
  495. resources.update(
  496. {
  497. MEDIA_PREFIX: media_repo,
  498. LEGACY_MEDIA_PREFIX: media_repo,
  499. "/_synapse/admin": admin_resource,
  500. }
  501. )
  502. else:
  503. logger.warning(
  504. "A 'media' listener is configured but the media"
  505. " repository is disabled. Ignoring."
  506. )
  507. if name == "openid" and "federation" not in res["names"]:
  508. # Only load the openid resource separately if federation resource
  509. # is not specified since federation resource includes openid
  510. # resource.
  511. resources.update(
  512. {
  513. FEDERATION_PREFIX: TransportLayerServer(
  514. self, servlet_groups=["openid"]
  515. )
  516. }
  517. )
  518. if name in ["keys", "federation"]:
  519. resources[SERVER_KEY_V2_PREFIX] = KeyApiV2Resource(self)
  520. if name == "replication":
  521. resources[REPLICATION_PREFIX] = ReplicationRestResource(self)
  522. root_resource = create_resource_tree(resources, OptionsResource())
  523. _base.listen_tcp(
  524. bind_addresses,
  525. port,
  526. SynapseSite(
  527. "synapse.access.http.%s" % (site_tag,),
  528. site_tag,
  529. listener_config,
  530. root_resource,
  531. self.version_string,
  532. ),
  533. reactor=self.get_reactor(),
  534. )
  535. logger.info("Synapse worker now listening on port %d", port)
  536. def start_listening(self, listeners):
  537. for listener in listeners:
  538. if listener["type"] == "http":
  539. self._listen_http(listener)
  540. elif listener["type"] == "manhole":
  541. _base.listen_tcp(
  542. listener["bind_addresses"],
  543. listener["port"],
  544. manhole(
  545. username="matrix", password="rabbithole", globals={"hs": self}
  546. ),
  547. )
  548. elif listener["type"] == "metrics":
  549. if not self.get_config().enable_metrics:
  550. logger.warning(
  551. (
  552. "Metrics listener configured, but "
  553. "enable_metrics is not True!"
  554. )
  555. )
  556. else:
  557. _base.listen_metrics(listener["bind_addresses"], listener["port"])
  558. else:
  559. logger.warning("Unrecognized listener type: %s", listener["type"])
  560. self.get_tcp_replication().start_replication(self)
  561. def remove_pusher(self, app_id, push_key, user_id):
  562. self.get_tcp_replication().send_remove_pusher(app_id, push_key, user_id)
  563. def build_replication_data_handler(self):
  564. return GenericWorkerReplicationHandler(self)
  565. def build_presence_handler(self):
  566. return GenericWorkerPresence(self)
  567. def build_typing_handler(self):
  568. return GenericWorkerTyping(self)
  569. class GenericWorkerReplicationHandler(ReplicationDataHandler):
  570. def __init__(self, hs):
  571. super(GenericWorkerReplicationHandler, self).__init__(hs)
  572. self.store = hs.get_datastore()
  573. self.typing_handler = hs.get_typing_handler()
  574. self.presence_handler = hs.get_presence_handler() # type: GenericWorkerPresence
  575. self.notifier = hs.get_notifier()
  576. self.notify_pushers = hs.config.start_pushers
  577. self.pusher_pool = hs.get_pusherpool()
  578. self.send_handler = None # type: Optional[FederationSenderHandler]
  579. if hs.config.send_federation:
  580. self.send_handler = FederationSenderHandler(hs)
  581. async def on_rdata(self, stream_name, instance_name, token, rows):
  582. await super().on_rdata(stream_name, instance_name, token, rows)
  583. await self._process_and_notify(stream_name, instance_name, token, rows)
  584. async def _process_and_notify(self, stream_name, instance_name, token, rows):
  585. try:
  586. if self.send_handler:
  587. await self.send_handler.process_replication_rows(
  588. stream_name, token, rows
  589. )
  590. if stream_name == PushRulesStream.NAME:
  591. self.notifier.on_new_event(
  592. "push_rules_key", token, users=[row.user_id for row in rows]
  593. )
  594. elif stream_name in (AccountDataStream.NAME, TagAccountDataStream.NAME):
  595. self.notifier.on_new_event(
  596. "account_data_key", token, users=[row.user_id for row in rows]
  597. )
  598. elif stream_name == ReceiptsStream.NAME:
  599. self.notifier.on_new_event(
  600. "receipt_key", token, rooms=[row.room_id for row in rows]
  601. )
  602. await self.pusher_pool.on_new_receipts(
  603. token, token, {row.room_id for row in rows}
  604. )
  605. elif stream_name == TypingStream.NAME:
  606. self.typing_handler.process_replication_rows(token, rows)
  607. self.notifier.on_new_event(
  608. "typing_key", token, rooms=[row.room_id for row in rows]
  609. )
  610. elif stream_name == ToDeviceStream.NAME:
  611. entities = [row.entity for row in rows if row.entity.startswith("@")]
  612. if entities:
  613. self.notifier.on_new_event("to_device_key", token, users=entities)
  614. elif stream_name == DeviceListsStream.NAME:
  615. all_room_ids = set() # type: Set[str]
  616. for row in rows:
  617. if row.entity.startswith("@"):
  618. room_ids = await self.store.get_rooms_for_user(row.entity)
  619. all_room_ids.update(room_ids)
  620. self.notifier.on_new_event("device_list_key", token, rooms=all_room_ids)
  621. elif stream_name == PresenceStream.NAME:
  622. await self.presence_handler.process_replication_rows(token, rows)
  623. elif stream_name == GroupServerStream.NAME:
  624. self.notifier.on_new_event(
  625. "groups_key", token, users=[row.user_id for row in rows]
  626. )
  627. elif stream_name == PushersStream.NAME:
  628. for row in rows:
  629. if row.deleted:
  630. self.stop_pusher(row.user_id, row.app_id, row.pushkey)
  631. else:
  632. await self.start_pusher(row.user_id, row.app_id, row.pushkey)
  633. except Exception:
  634. logger.exception("Error processing replication")
  635. def stop_pusher(self, user_id, app_id, pushkey):
  636. if not self.notify_pushers:
  637. return
  638. key = "%s:%s" % (app_id, pushkey)
  639. pushers_for_user = self.pusher_pool.pushers.get(user_id, {})
  640. pusher = pushers_for_user.pop(key, None)
  641. if pusher is None:
  642. return
  643. logger.info("Stopping pusher %r / %r", user_id, key)
  644. pusher.on_stop()
  645. async def start_pusher(self, user_id, app_id, pushkey):
  646. if not self.notify_pushers:
  647. return
  648. key = "%s:%s" % (app_id, pushkey)
  649. logger.info("Starting pusher %r / %r", user_id, key)
  650. return await self.pusher_pool.start_pusher_by_id(app_id, pushkey, user_id)
  651. def on_remote_server_up(self, server: str):
  652. """Called when get a new REMOTE_SERVER_UP command."""
  653. # Let's wake up the transaction queue for the server in case we have
  654. # pending stuff to send to it.
  655. if self.send_handler:
  656. self.send_handler.wake_destination(server)
  657. class FederationSenderHandler(object):
  658. """Processes the fedration replication stream
  659. This class is only instantiate on the worker responsible for sending outbound
  660. federation transactions. It receives rows from the replication stream and forwards
  661. the appropriate entries to the FederationSender class.
  662. """
  663. def __init__(self, hs: GenericWorkerServer):
  664. self.store = hs.get_datastore()
  665. self._is_mine_id = hs.is_mine_id
  666. self.federation_sender = hs.get_federation_sender()
  667. self._hs = hs
  668. # if the worker is restarted, we want to pick up where we left off in
  669. # the replication stream, so load the position from the database.
  670. #
  671. # XXX is this actually worthwhile? Whenever the master is restarted, we'll
  672. # drop some rows anyway (which is mostly fine because we're only dropping
  673. # typing and presence notifications). If the replication stream is
  674. # unreliable, why do we do all this hoop-jumping to store the position in the
  675. # database? See also https://github.com/matrix-org/synapse/issues/7535.
  676. #
  677. self.federation_position = self.store.federation_out_pos_startup
  678. self._fed_position_linearizer = Linearizer(name="_fed_position_linearizer")
  679. self._last_ack = self.federation_position
  680. def on_start(self):
  681. # There may be some events that are persisted but haven't been sent,
  682. # so send them now.
  683. self.federation_sender.notify_new_events(
  684. self.store.get_room_max_stream_ordering()
  685. )
  686. def wake_destination(self, server: str):
  687. self.federation_sender.wake_destination(server)
  688. async def process_replication_rows(self, stream_name, token, rows):
  689. # The federation stream contains things that we want to send out, e.g.
  690. # presence, typing, etc.
  691. if stream_name == "federation":
  692. send_queue.process_rows_for_federation(self.federation_sender, rows)
  693. await self.update_token(token)
  694. # We also need to poke the federation sender when new events happen
  695. elif stream_name == "events":
  696. self.federation_sender.notify_new_events(token)
  697. # ... and when new receipts happen
  698. elif stream_name == ReceiptsStream.NAME:
  699. await self._on_new_receipts(rows)
  700. # ... as well as device updates and messages
  701. elif stream_name == DeviceListsStream.NAME:
  702. # The entities are either user IDs (starting with '@') whose devices
  703. # have changed, or remote servers that we need to tell about
  704. # changes.
  705. hosts = {row.entity for row in rows if not row.entity.startswith("@")}
  706. for host in hosts:
  707. self.federation_sender.send_device_messages(host)
  708. elif stream_name == ToDeviceStream.NAME:
  709. # The to_device stream includes stuff to be pushed to both local
  710. # clients and remote servers, so we ignore entities that start with
  711. # '@' (since they'll be local users rather than destinations).
  712. hosts = {row.entity for row in rows if not row.entity.startswith("@")}
  713. for host in hosts:
  714. self.federation_sender.send_device_messages(host)
  715. async def _on_new_receipts(self, rows):
  716. """
  717. Args:
  718. rows (Iterable[synapse.replication.tcp.streams.ReceiptsStream.ReceiptsStreamRow]):
  719. new receipts to be processed
  720. """
  721. for receipt in rows:
  722. # we only want to send on receipts for our own users
  723. if not self._is_mine_id(receipt.user_id):
  724. continue
  725. receipt_info = ReadReceipt(
  726. receipt.room_id,
  727. receipt.receipt_type,
  728. receipt.user_id,
  729. [receipt.event_id],
  730. receipt.data,
  731. )
  732. await self.federation_sender.send_read_receipt(receipt_info)
  733. async def update_token(self, token):
  734. """Update the record of where we have processed to in the federation stream.
  735. Called after we have processed a an update received over replication. Sends
  736. a FEDERATION_ACK back to the master, and stores the token that we have processed
  737. in `federation_stream_position` so that we can restart where we left off.
  738. """
  739. self.federation_position = token
  740. # We save and send the ACK to master asynchronously, so we don't block
  741. # processing on persistence. We don't need to do this operation for
  742. # every single RDATA we receive, we just need to do it periodically.
  743. if self._fed_position_linearizer.is_queued(None):
  744. # There is already a task queued up to save and send the token, so
  745. # no need to queue up another task.
  746. return
  747. run_as_background_process("_save_and_send_ack", self._save_and_send_ack)
  748. async def _save_and_send_ack(self):
  749. """Save the current federation position in the database and send an ACK
  750. to master with where we're up to.
  751. """
  752. try:
  753. # We linearize here to ensure we don't have races updating the token
  754. #
  755. # XXX this appears to be redundant, since the ReplicationCommandHandler
  756. # has a linearizer which ensures that we only process one line of
  757. # replication data at a time. Should we remove it, or is it doing useful
  758. # service for robustness? Or could we replace it with an assertion that
  759. # we're not being re-entered?
  760. with (await self._fed_position_linearizer.queue(None)):
  761. # We persist and ack the same position, so we take a copy of it
  762. # here as otherwise it can get modified from underneath us.
  763. current_position = self.federation_position
  764. await self.store.update_federation_out_pos(
  765. "federation", current_position
  766. )
  767. # We ACK this token over replication so that the master can drop
  768. # its in memory queues
  769. self._hs.get_tcp_replication().send_federation_ack(current_position)
  770. self._last_ack = current_position
  771. except Exception:
  772. logger.exception("Error updating federation stream position")
  773. def start(config_options):
  774. try:
  775. config = HomeServerConfig.load_config("Synapse worker", config_options)
  776. except ConfigError as e:
  777. sys.stderr.write("\n" + str(e) + "\n")
  778. sys.exit(1)
  779. # For backwards compatibility let any of the old app names.
  780. assert config.worker_app in (
  781. "synapse.app.appservice",
  782. "synapse.app.client_reader",
  783. "synapse.app.event_creator",
  784. "synapse.app.federation_reader",
  785. "synapse.app.federation_sender",
  786. "synapse.app.frontend_proxy",
  787. "synapse.app.generic_worker",
  788. "synapse.app.media_repository",
  789. "synapse.app.pusher",
  790. "synapse.app.synchrotron",
  791. "synapse.app.user_dir",
  792. )
  793. if config.worker_app == "synapse.app.appservice":
  794. if config.notify_appservices:
  795. sys.stderr.write(
  796. "\nThe appservices must be disabled in the main synapse process"
  797. "\nbefore they can be run in a separate worker."
  798. "\nPlease add ``notify_appservices: false`` to the main config"
  799. "\n"
  800. )
  801. sys.exit(1)
  802. # Force the appservice to start since they will be disabled in the main config
  803. config.notify_appservices = True
  804. else:
  805. # For other worker types we force this to off.
  806. config.notify_appservices = False
  807. if config.worker_app == "synapse.app.pusher":
  808. if config.start_pushers:
  809. sys.stderr.write(
  810. "\nThe pushers must be disabled in the main synapse process"
  811. "\nbefore they can be run in a separate worker."
  812. "\nPlease add ``start_pushers: false`` to the main config"
  813. "\n"
  814. )
  815. sys.exit(1)
  816. # Force the pushers to start since they will be disabled in the main config
  817. config.start_pushers = True
  818. else:
  819. # For other worker types we force this to off.
  820. config.start_pushers = False
  821. if config.worker_app == "synapse.app.user_dir":
  822. if config.update_user_directory:
  823. sys.stderr.write(
  824. "\nThe update_user_directory must be disabled in the main synapse process"
  825. "\nbefore they can be run in a separate worker."
  826. "\nPlease add ``update_user_directory: false`` to the main config"
  827. "\n"
  828. )
  829. sys.exit(1)
  830. # Force the pushers to start since they will be disabled in the main config
  831. config.update_user_directory = True
  832. else:
  833. # For other worker types we force this to off.
  834. config.update_user_directory = False
  835. if config.worker_app == "synapse.app.federation_sender":
  836. if config.send_federation:
  837. sys.stderr.write(
  838. "\nThe send_federation must be disabled in the main synapse process"
  839. "\nbefore they can be run in a separate worker."
  840. "\nPlease add ``send_federation: false`` to the main config"
  841. "\n"
  842. )
  843. sys.exit(1)
  844. # Force the pushers to start since they will be disabled in the main config
  845. config.send_federation = True
  846. else:
  847. # For other worker types we force this to off.
  848. config.send_federation = False
  849. synapse.events.USE_FROZEN_DICTS = config.use_frozen_dicts
  850. hs = GenericWorkerServer(
  851. config.server_name,
  852. config=config,
  853. version_string="Synapse/" + get_version_string(synapse),
  854. )
  855. setup_logging(hs, config, use_worker_options=True)
  856. hs.setup()
  857. # Ensure the replication streamer is always started in case we write to any
  858. # streams. Will no-op if no streams can be written to by this worker.
  859. hs.get_replication_streamer()
  860. reactor.addSystemEventTrigger(
  861. "before", "startup", _base.start, hs, config.worker_listeners
  862. )
  863. _base.start_worker_reactor("synapse-generic-worker", config)
  864. if __name__ == "__main__":
  865. with LoggingContext("main"):
  866. start(sys.argv[1:])