generic_worker.py 41 KB

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