You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1085 lines
43 KiB

  1. #!/usr/bin/env python
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # This script reads environment variables and generates a shared Synapse worker,
  16. # nginx and supervisord configs depending on the workers requested.
  17. #
  18. # The environment variables it reads are:
  19. # * SYNAPSE_SERVER_NAME: The desired server_name of the homeserver.
  20. # * SYNAPSE_REPORT_STATS: Whether to report stats.
  21. # * SYNAPSE_WORKER_TYPES: A comma separated list of worker names as specified in WORKERS_CONFIG
  22. # below. Leave empty for no workers. Add a ':' and a number at the end to
  23. # multiply that worker. Append multiple worker types with '+' to merge the
  24. # worker types into a single worker. Add a name and a '=' to the front of a
  25. # worker type to give this instance a name in logs and nginx.
  26. # Examples:
  27. # SYNAPSE_WORKER_TYPES='event_persister, federation_sender, client_reader'
  28. # SYNAPSE_WORKER_TYPES='event_persister:2, federation_sender:2, client_reader'
  29. # SYNAPSE_WORKER_TYPES='stream_writers=account_data+presence+typing'
  30. # * SYNAPSE_AS_REGISTRATION_DIR: If specified, a directory in which .yaml and .yml files
  31. # will be treated as Application Service registration files.
  32. # * SYNAPSE_TLS_CERT: Path to a TLS certificate in PEM format.
  33. # * SYNAPSE_TLS_KEY: Path to a TLS key. If this and SYNAPSE_TLS_CERT are specified,
  34. # Nginx will be configured to serve TLS on port 8448.
  35. # * SYNAPSE_USE_EXPERIMENTAL_FORKING_LAUNCHER: Whether to use the forking launcher,
  36. # only intended for usage in Complement at the moment.
  37. # No stability guarantees are provided.
  38. # * SYNAPSE_LOG_LEVEL: Set this to DEBUG, INFO, WARNING or ERROR to change the
  39. # log level. INFO is the default.
  40. # * SYNAPSE_LOG_SENSITIVE: If unset, SQL and SQL values won't be logged,
  41. # regardless of the SYNAPSE_LOG_LEVEL setting.
  42. # * SYNAPSE_LOG_TESTING: if set, Synapse will log additional information useful
  43. # for testing.
  44. #
  45. # NOTE: According to Complement's ENTRYPOINT expectations for a homeserver image (as defined
  46. # in the project's README), this script may be run multiple times, and functionality should
  47. # continue to work if so.
  48. import os
  49. import platform
  50. import re
  51. import subprocess
  52. import sys
  53. from collections import defaultdict
  54. from itertools import chain
  55. from pathlib import Path
  56. from typing import (
  57. Any,
  58. Dict,
  59. List,
  60. Mapping,
  61. MutableMapping,
  62. NoReturn,
  63. Optional,
  64. Set,
  65. SupportsIndex,
  66. )
  67. import yaml
  68. from jinja2 import Environment, FileSystemLoader
  69. MAIN_PROCESS_HTTP_LISTENER_PORT = 8080
  70. MAIN_PROCESS_INSTANCE_NAME = "main"
  71. MAIN_PROCESS_LOCALHOST_ADDRESS = "127.0.0.1"
  72. MAIN_PROCESS_REPLICATION_PORT = 9093
  73. # Obviously, these would only be used with the UNIX socket option
  74. MAIN_PROCESS_UNIX_SOCKET_PUBLIC_PATH = "/run/main_public.sock"
  75. MAIN_PROCESS_UNIX_SOCKET_PRIVATE_PATH = "/run/main_private.sock"
  76. # A simple name used as a placeholder in the WORKERS_CONFIG below. This will be replaced
  77. # during processing with the name of the worker.
  78. WORKER_PLACEHOLDER_NAME = "placeholder_name"
  79. # Workers with exposed endpoints needs either "client", "federation", or "media" listener_resources
  80. # Watching /_matrix/client needs a "client" listener
  81. # Watching /_matrix/federation needs a "federation" listener
  82. # Watching /_matrix/media and related needs a "media" listener
  83. # Stream Writers require "client" and "replication" listeners because they
  84. # have to attach by instance_map to the master process and have client endpoints.
  85. WORKERS_CONFIG: Dict[str, Dict[str, Any]] = {
  86. "pusher": {
  87. "app": "synapse.app.generic_worker",
  88. "listener_resources": [],
  89. "endpoint_patterns": [],
  90. "shared_extra_conf": {},
  91. "worker_extra_conf": "",
  92. },
  93. "user_dir": {
  94. "app": "synapse.app.generic_worker",
  95. "listener_resources": ["client"],
  96. "endpoint_patterns": [
  97. "^/_matrix/client/(api/v1|r0|v3|unstable)/user_directory/search$"
  98. ],
  99. "shared_extra_conf": {
  100. "update_user_directory_from_worker": WORKER_PLACEHOLDER_NAME
  101. },
  102. "worker_extra_conf": "",
  103. },
  104. "media_repository": {
  105. "app": "synapse.app.generic_worker",
  106. "listener_resources": ["media"],
  107. "endpoint_patterns": [
  108. "^/_matrix/media/",
  109. "^/_synapse/admin/v1/purge_media_cache$",
  110. "^/_synapse/admin/v1/room/.*/media.*$",
  111. "^/_synapse/admin/v1/user/.*/media.*$",
  112. "^/_synapse/admin/v1/media/.*$",
  113. "^/_synapse/admin/v1/quarantine_media/.*$",
  114. ],
  115. # The first configured media worker will run the media background jobs
  116. "shared_extra_conf": {
  117. "enable_media_repo": False,
  118. "media_instance_running_background_jobs": WORKER_PLACEHOLDER_NAME,
  119. },
  120. "worker_extra_conf": "enable_media_repo: true",
  121. },
  122. "appservice": {
  123. "app": "synapse.app.generic_worker",
  124. "listener_resources": [],
  125. "endpoint_patterns": [],
  126. "shared_extra_conf": {
  127. "notify_appservices_from_worker": WORKER_PLACEHOLDER_NAME
  128. },
  129. "worker_extra_conf": "",
  130. },
  131. "federation_sender": {
  132. "app": "synapse.app.generic_worker",
  133. "listener_resources": [],
  134. "endpoint_patterns": [],
  135. "shared_extra_conf": {},
  136. "worker_extra_conf": "",
  137. },
  138. "synchrotron": {
  139. "app": "synapse.app.generic_worker",
  140. "listener_resources": ["client"],
  141. "endpoint_patterns": [
  142. "^/_matrix/client/(v2_alpha|r0|v3)/sync$",
  143. "^/_matrix/client/(api/v1|v2_alpha|r0|v3)/events$",
  144. "^/_matrix/client/(api/v1|r0|v3)/initialSync$",
  145. "^/_matrix/client/(api/v1|r0|v3)/rooms/[^/]+/initialSync$",
  146. ],
  147. "shared_extra_conf": {},
  148. "worker_extra_conf": "",
  149. },
  150. "client_reader": {
  151. "app": "synapse.app.generic_worker",
  152. "listener_resources": ["client"],
  153. "endpoint_patterns": [
  154. "^/_matrix/client/(api/v1|r0|v3|unstable)/publicRooms$",
  155. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/joined_members$",
  156. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/context/.*$",
  157. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/members$",
  158. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state$",
  159. "^/_matrix/client/v1/rooms/.*/hierarchy$",
  160. "^/_matrix/client/(v1|unstable)/rooms/.*/relations/",
  161. "^/_matrix/client/v1/rooms/.*/threads$",
  162. "^/_matrix/client/(api/v1|r0|v3|unstable)/login$",
  163. "^/_matrix/client/(api/v1|r0|v3|unstable)/account/3pid$",
  164. "^/_matrix/client/(api/v1|r0|v3|unstable)/account/whoami$",
  165. "^/_matrix/client/versions$",
  166. "^/_matrix/client/(api/v1|r0|v3|unstable)/voip/turnServer$",
  167. "^/_matrix/client/(r0|v3|unstable)/register$",
  168. "^/_matrix/client/(r0|v3|unstable)/register/available$",
  169. "^/_matrix/client/(r0|v3|unstable)/auth/.*/fallback/web$",
  170. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/messages$",
  171. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/event",
  172. "^/_matrix/client/(api/v1|r0|v3|unstable)/joined_rooms",
  173. "^/_matrix/client/(api/v1|r0|v3|unstable/.*)/rooms/.*/aliases",
  174. "^/_matrix/client/v1/rooms/.*/timestamp_to_event$",
  175. "^/_matrix/client/(api/v1|r0|v3|unstable)/search",
  176. "^/_matrix/client/(r0|v3|unstable)/user/.*/filter(/|$)",
  177. "^/_matrix/client/(r0|v3|unstable)/password_policy$",
  178. "^/_matrix/client/(api/v1|r0|v3|unstable)/directory/room/.*$",
  179. "^/_matrix/client/(r0|v3|unstable)/capabilities$",
  180. "^/_matrix/client/(r0|v3|unstable)/notifications$",
  181. ],
  182. "shared_extra_conf": {},
  183. "worker_extra_conf": "",
  184. },
  185. "federation_reader": {
  186. "app": "synapse.app.generic_worker",
  187. "listener_resources": ["federation"],
  188. "endpoint_patterns": [
  189. "^/_matrix/federation/(v1|v2)/event/",
  190. "^/_matrix/federation/(v1|v2)/state/",
  191. "^/_matrix/federation/(v1|v2)/state_ids/",
  192. "^/_matrix/federation/(v1|v2)/backfill/",
  193. "^/_matrix/federation/(v1|v2)/get_missing_events/",
  194. "^/_matrix/federation/(v1|v2)/publicRooms",
  195. "^/_matrix/federation/(v1|v2)/query/",
  196. "^/_matrix/federation/(v1|v2)/make_join/",
  197. "^/_matrix/federation/(v1|v2)/make_leave/",
  198. "^/_matrix/federation/(v1|v2)/send_join/",
  199. "^/_matrix/federation/(v1|v2)/send_leave/",
  200. "^/_matrix/federation/(v1|v2)/invite/",
  201. "^/_matrix/federation/(v1|v2)/query_auth/",
  202. "^/_matrix/federation/(v1|v2)/event_auth/",
  203. "^/_matrix/federation/v1/timestamp_to_event/",
  204. "^/_matrix/federation/(v1|v2)/exchange_third_party_invite/",
  205. "^/_matrix/federation/(v1|v2)/user/devices/",
  206. "^/_matrix/federation/(v1|v2)/get_groups_publicised$",
  207. "^/_matrix/key/v2/query",
  208. ],
  209. "shared_extra_conf": {},
  210. "worker_extra_conf": "",
  211. },
  212. "federation_inbound": {
  213. "app": "synapse.app.generic_worker",
  214. "listener_resources": ["federation"],
  215. "endpoint_patterns": ["/_matrix/federation/(v1|v2)/send/"],
  216. "shared_extra_conf": {},
  217. "worker_extra_conf": "",
  218. },
  219. "event_persister": {
  220. "app": "synapse.app.generic_worker",
  221. "listener_resources": ["replication"],
  222. "endpoint_patterns": [],
  223. "shared_extra_conf": {},
  224. "worker_extra_conf": "",
  225. },
  226. "background_worker": {
  227. "app": "synapse.app.generic_worker",
  228. "listener_resources": [],
  229. "endpoint_patterns": [],
  230. # This worker cannot be sharded. Therefore, there should only ever be one
  231. # background worker. This is enforced for the safety of your database.
  232. "shared_extra_conf": {"run_background_tasks_on": WORKER_PLACEHOLDER_NAME},
  233. "worker_extra_conf": "",
  234. },
  235. "event_creator": {
  236. "app": "synapse.app.generic_worker",
  237. "listener_resources": ["client"],
  238. "endpoint_patterns": [
  239. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/redact",
  240. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/send",
  241. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/(join|invite|leave|ban|unban|kick)$",
  242. "^/_matrix/client/(api/v1|r0|v3|unstable)/join/",
  243. "^/_matrix/client/(api/v1|r0|v3|unstable)/knock/",
  244. "^/_matrix/client/(api/v1|r0|v3|unstable)/profile/",
  245. ],
  246. "shared_extra_conf": {},
  247. "worker_extra_conf": "",
  248. },
  249. "frontend_proxy": {
  250. "app": "synapse.app.generic_worker",
  251. "listener_resources": ["client", "replication"],
  252. "endpoint_patterns": ["^/_matrix/client/(api/v1|r0|v3|unstable)/keys/upload"],
  253. "shared_extra_conf": {},
  254. "worker_extra_conf": "",
  255. },
  256. "account_data": {
  257. "app": "synapse.app.generic_worker",
  258. "listener_resources": ["client", "replication"],
  259. "endpoint_patterns": [
  260. "^/_matrix/client/(r0|v3|unstable)/.*/tags",
  261. "^/_matrix/client/(r0|v3|unstable)/.*/account_data",
  262. ],
  263. "shared_extra_conf": {},
  264. "worker_extra_conf": "",
  265. },
  266. "presence": {
  267. "app": "synapse.app.generic_worker",
  268. "listener_resources": ["client", "replication"],
  269. "endpoint_patterns": ["^/_matrix/client/(api/v1|r0|v3|unstable)/presence/"],
  270. "shared_extra_conf": {},
  271. "worker_extra_conf": "",
  272. },
  273. "receipts": {
  274. "app": "synapse.app.generic_worker",
  275. "listener_resources": ["client", "replication"],
  276. "endpoint_patterns": [
  277. "^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt",
  278. "^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers",
  279. ],
  280. "shared_extra_conf": {},
  281. "worker_extra_conf": "",
  282. },
  283. "to_device": {
  284. "app": "synapse.app.generic_worker",
  285. "listener_resources": ["client", "replication"],
  286. "endpoint_patterns": ["^/_matrix/client/(r0|v3|unstable)/sendToDevice/"],
  287. "shared_extra_conf": {},
  288. "worker_extra_conf": "",
  289. },
  290. "typing": {
  291. "app": "synapse.app.generic_worker",
  292. "listener_resources": ["client", "replication"],
  293. "endpoint_patterns": [
  294. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/typing"
  295. ],
  296. "shared_extra_conf": {},
  297. "worker_extra_conf": "",
  298. },
  299. }
  300. # Templates for sections that may be inserted multiple times in config files
  301. NGINX_LOCATION_CONFIG_BLOCK = """
  302. location ~* {endpoint} {{
  303. proxy_pass {upstream};
  304. proxy_set_header X-Forwarded-For $remote_addr;
  305. proxy_set_header X-Forwarded-Proto $scheme;
  306. proxy_set_header Host $host;
  307. }}
  308. """
  309. NGINX_UPSTREAM_CONFIG_BLOCK = """
  310. upstream {upstream_worker_base_name} {{
  311. {body}
  312. }}
  313. """
  314. # Utility functions
  315. def log(txt: str) -> None:
  316. print(txt)
  317. def error(txt: str) -> NoReturn:
  318. print(txt, file=sys.stderr)
  319. sys.exit(2)
  320. def flush_buffers() -> None:
  321. sys.stdout.flush()
  322. sys.stderr.flush()
  323. def convert(src: str, dst: str, **template_vars: object) -> None:
  324. """Generate a file from a template
  325. Args:
  326. src: Path to the input file.
  327. dst: Path to write to.
  328. template_vars: The arguments to replace placeholder variables in the template with.
  329. """
  330. # Read the template file
  331. # We disable autoescape to prevent template variables from being escaped,
  332. # as we're not using HTML.
  333. env = Environment(loader=FileSystemLoader(os.path.dirname(src)), autoescape=False)
  334. template = env.get_template(os.path.basename(src))
  335. # Generate a string from the template.
  336. rendered = template.render(**template_vars)
  337. # Write the generated contents to a file
  338. #
  339. # We use append mode in case the files have already been written to by something else
  340. # (for instance, as part of the instructions in a dockerfile).
  341. with open(dst, "a") as outfile:
  342. # In case the existing file doesn't end with a newline
  343. outfile.write("\n")
  344. outfile.write(rendered)
  345. def add_worker_roles_to_shared_config(
  346. shared_config: dict,
  347. worker_types_set: Set[str],
  348. worker_name: str,
  349. worker_port: int,
  350. ) -> None:
  351. """Given a dictionary representing a config file shared across all workers,
  352. append appropriate worker information to it for the current worker_type instance.
  353. Args:
  354. shared_config: The config dict that all worker instances share (after being
  355. converted to YAML)
  356. worker_types_set: The type of worker (one of those defined in WORKERS_CONFIG).
  357. This list can be a single worker type or multiple.
  358. worker_name: The name of the worker instance.
  359. worker_port: The HTTP replication port that the worker instance is listening on.
  360. """
  361. # The instance_map config field marks the workers that write to various replication
  362. # streams
  363. instance_map = shared_config.setdefault("instance_map", {})
  364. # This is a list of the stream_writers that there can be only one of. Events can be
  365. # sharded, and therefore doesn't belong here.
  366. singular_stream_writers = [
  367. "account_data",
  368. "presence",
  369. "receipts",
  370. "to_device",
  371. "typing",
  372. ]
  373. # Worker-type specific sharding config. Now a single worker can fulfill multiple
  374. # roles, check each.
  375. if "pusher" in worker_types_set:
  376. shared_config.setdefault("pusher_instances", []).append(worker_name)
  377. if "federation_sender" in worker_types_set:
  378. shared_config.setdefault("federation_sender_instances", []).append(worker_name)
  379. if "event_persister" in worker_types_set:
  380. # Event persisters write to the events stream, so we need to update
  381. # the list of event stream writers
  382. shared_config.setdefault("stream_writers", {}).setdefault("events", []).append(
  383. worker_name
  384. )
  385. # Map of stream writer instance names to host/ports combos
  386. if os.environ.get("SYNAPSE_USE_UNIX_SOCKET", False):
  387. instance_map[worker_name] = {
  388. "path": f"/run/worker.{worker_port}",
  389. }
  390. else:
  391. instance_map[worker_name] = {
  392. "host": "localhost",
  393. "port": worker_port,
  394. }
  395. # Update the list of stream writers. It's convenient that the name of the worker
  396. # type is the same as the stream to write. Iterate over the whole list in case there
  397. # is more than one.
  398. for worker in worker_types_set:
  399. if worker in singular_stream_writers:
  400. shared_config.setdefault("stream_writers", {}).setdefault(
  401. worker, []
  402. ).append(worker_name)
  403. # Map of stream writer instance names to host/ports combos
  404. # For now, all stream writers need http replication ports
  405. if os.environ.get("SYNAPSE_USE_UNIX_SOCKET", False):
  406. instance_map[worker_name] = {
  407. "path": f"/run/worker.{worker_port}",
  408. }
  409. else:
  410. instance_map[worker_name] = {
  411. "host": "localhost",
  412. "port": worker_port,
  413. }
  414. def merge_worker_template_configs(
  415. existing_dict: Optional[Dict[str, Any]],
  416. to_be_merged_dict: Dict[str, Any],
  417. ) -> Dict[str, Any]:
  418. """When given an existing dict of worker template configuration consisting with both
  419. dicts and lists, merge new template data from WORKERS_CONFIG(or create) and
  420. return new dict.
  421. Args:
  422. existing_dict: Either an existing worker template or a fresh blank one.
  423. to_be_merged_dict: The template from WORKERS_CONFIGS to be merged into
  424. existing_dict.
  425. Returns: The newly merged together dict values.
  426. """
  427. new_dict: Dict[str, Any] = {}
  428. if not existing_dict:
  429. # It doesn't exist yet, just use the new dict(but take a copy not a reference)
  430. new_dict = to_be_merged_dict.copy()
  431. else:
  432. for i in to_be_merged_dict.keys():
  433. if (i == "endpoint_patterns") or (i == "listener_resources"):
  434. # merge the two lists, remove duplicates
  435. new_dict[i] = list(set(existing_dict[i] + to_be_merged_dict[i]))
  436. elif i == "shared_extra_conf":
  437. # merge dictionary's, the worker name will be replaced later
  438. new_dict[i] = {**existing_dict[i], **to_be_merged_dict[i]}
  439. elif i == "worker_extra_conf":
  440. # There is only one worker type that has a 'worker_extra_conf' and it is
  441. # the media_repo. Since duplicate worker types on the same worker don't
  442. # work, this is fine.
  443. new_dict[i] = existing_dict[i] + to_be_merged_dict[i]
  444. else:
  445. # Everything else should be identical, like "app", which only works
  446. # because all apps are now generic_workers.
  447. new_dict[i] = to_be_merged_dict[i]
  448. return new_dict
  449. def insert_worker_name_for_worker_config(
  450. existing_dict: Dict[str, Any], worker_name: str
  451. ) -> Dict[str, Any]:
  452. """Insert a given worker name into the worker's configuration dict.
  453. Args:
  454. existing_dict: The worker_config dict that is imported into shared_config.
  455. worker_name: The name of the worker to insert.
  456. Returns: Copy of the dict with newly inserted worker name
  457. """
  458. dict_to_edit = existing_dict.copy()
  459. for k, v in dict_to_edit["shared_extra_conf"].items():
  460. # Only proceed if it's the placeholder name string
  461. if v == WORKER_PLACEHOLDER_NAME:
  462. dict_to_edit["shared_extra_conf"][k] = worker_name
  463. return dict_to_edit
  464. def apply_requested_multiplier_for_worker(worker_types: List[str]) -> List[str]:
  465. """
  466. Apply multiplier(if found) by returning a new expanded list with some basic error
  467. checking.
  468. Args:
  469. worker_types: The unprocessed List of requested workers
  470. Returns:
  471. A new list with all requested workers expanded.
  472. """
  473. # Checking performed:
  474. # 1. if worker:2 or more is declared, it will create additional workers up to number
  475. # 2. if worker:1, it will create a single copy of this worker as if no number was
  476. # given
  477. # 3. if worker:0 is declared, this worker will be ignored. This is to allow for
  478. # scripting and automated expansion and is intended behaviour.
  479. # 4. if worker:NaN or is a negative number, it will error and log it.
  480. new_worker_types = []
  481. for worker_type in worker_types:
  482. if ":" in worker_type:
  483. worker_type_components = split_and_strip_string(worker_type, ":", 1)
  484. worker_count = 0
  485. # Should only be 2 components, a type of worker(s) and an integer as a
  486. # string. Cast the number as an int then it can be used as a counter.
  487. try:
  488. worker_count = int(worker_type_components[1])
  489. except ValueError:
  490. error(
  491. f"Bad number in worker count for '{worker_type}': "
  492. f"'{worker_type_components[1]}' is not an integer"
  493. )
  494. # As long as there are more than 0, we add one to the list to make below.
  495. for _ in range(worker_count):
  496. new_worker_types.append(worker_type_components[0])
  497. else:
  498. # If it's not a real worker_type, it will error out later.
  499. new_worker_types.append(worker_type)
  500. return new_worker_types
  501. def is_sharding_allowed_for_worker_type(worker_type: str) -> bool:
  502. """Helper to check to make sure worker types that cannot have multiples do not.
  503. Args:
  504. worker_type: The type of worker to check against.
  505. Returns: True if allowed, False if not
  506. """
  507. return worker_type not in [
  508. "background_worker",
  509. "account_data",
  510. "presence",
  511. "receipts",
  512. "typing",
  513. "to_device",
  514. ]
  515. def split_and_strip_string(
  516. given_string: str, split_char: str, max_split: SupportsIndex = -1
  517. ) -> List[str]:
  518. """
  519. Helper to split a string on split_char and strip whitespace from each end of each
  520. element.
  521. Args:
  522. given_string: The string to split
  523. split_char: The character to split the string on
  524. max_split: kwarg for split() to limit how many times the split() happens
  525. Returns:
  526. A List of strings
  527. """
  528. # Removes whitespace from ends of result strings before adding to list. Allow for
  529. # overriding 'maxsplit' kwarg, default being -1 to signify no maximum.
  530. return [x.strip() for x in given_string.split(split_char, maxsplit=max_split)]
  531. def generate_base_homeserver_config() -> None:
  532. """Starts Synapse and generates a basic homeserver config, which will later be
  533. modified for worker support.
  534. Raises: CalledProcessError if calling start.py returned a non-zero exit code.
  535. """
  536. # start.py already does this for us, so just call that.
  537. # note that this script is copied in in the official, monolith dockerfile
  538. os.environ["SYNAPSE_HTTP_PORT"] = str(MAIN_PROCESS_HTTP_LISTENER_PORT)
  539. subprocess.run(["/usr/local/bin/python", "/start.py", "migrate_config"], check=True)
  540. def parse_worker_types(
  541. requested_worker_types: List[str],
  542. ) -> Dict[str, Set[str]]:
  543. """Read the desired list of requested workers and prepare the data for use in
  544. generating worker config files while also checking for potential gotchas.
  545. Args:
  546. requested_worker_types: The list formed from the split environment variable
  547. containing the unprocessed requests for workers.
  548. Returns: A dict of worker names to set of worker types. Format:
  549. {'worker_name':
  550. {'worker_type', 'worker_type2'}
  551. }
  552. """
  553. # A counter of worker_base_name -> int. Used for determining the name for a given
  554. # worker when generating its config file, as each worker's name is just
  555. # worker_base_name followed by instance number
  556. worker_base_name_counter: Dict[str, int] = defaultdict(int)
  557. # Similar to above, but more finely grained. This is used to determine we don't have
  558. # more than a single worker for cases where multiples would be bad(e.g. presence).
  559. worker_type_shard_counter: Dict[str, int] = defaultdict(int)
  560. # The final result of all this processing
  561. dict_to_return: Dict[str, Set[str]] = {}
  562. # Handle any multipliers requested for given workers.
  563. multiple_processed_worker_types = apply_requested_multiplier_for_worker(
  564. requested_worker_types
  565. )
  566. # Process each worker_type_string
  567. # Examples of expected formats:
  568. # - requested_name=type1+type2+type3
  569. # - synchrotron
  570. # - event_creator+event_persister
  571. for worker_type_string in multiple_processed_worker_types:
  572. # First, if a name is requested, use that — otherwise generate one.
  573. worker_base_name: str = ""
  574. if "=" in worker_type_string:
  575. # Split on "=", remove extra whitespace from ends then make list
  576. worker_type_split = split_and_strip_string(worker_type_string, "=")
  577. if len(worker_type_split) > 2:
  578. error(
  579. "There should only be one '=' in the worker type string. "
  580. f"Please fix: {worker_type_string}"
  581. )
  582. # Assign the name
  583. worker_base_name = worker_type_split[0]
  584. if not re.match(r"^[a-zA-Z0-9_+-]*[a-zA-Z_+-]$", worker_base_name):
  585. # Apply a fairly narrow regex to the worker names. Some characters
  586. # aren't safe for use in file paths or nginx configurations.
  587. # Don't allow to end with a number because we'll add a number
  588. # ourselves in a moment.
  589. error(
  590. "Invalid worker name; please choose a name consisting of "
  591. "alphanumeric letters, _ + -, but not ending with a digit: "
  592. f"{worker_base_name!r}"
  593. )
  594. # Continue processing the remainder of the worker_type string
  595. # with the name override removed.
  596. worker_type_string = worker_type_split[1]
  597. # Split the worker_type_string on "+", remove whitespace from ends then make
  598. # the list a set so it's deduplicated.
  599. worker_types_set: Set[str] = set(
  600. split_and_strip_string(worker_type_string, "+")
  601. )
  602. if not worker_base_name:
  603. # No base name specified: generate one deterministically from set of
  604. # types
  605. worker_base_name = "+".join(sorted(worker_types_set))
  606. # At this point, we have:
  607. # worker_base_name which is the name for the worker, without counter.
  608. # worker_types_set which is the set of worker types for this worker.
  609. # Validate worker_type and make sure we don't allow sharding for a worker type
  610. # that doesn't support it. Will error and stop if it is a problem,
  611. # e.g. 'background_worker'.
  612. for worker_type in worker_types_set:
  613. # Verify this is a real defined worker type. If it's not, stop everything so
  614. # it can be fixed.
  615. if worker_type not in WORKERS_CONFIG:
  616. error(
  617. f"{worker_type} is an unknown worker type! Was found in "
  618. f"'{worker_type_string}'. Please fix!"
  619. )
  620. if worker_type in worker_type_shard_counter:
  621. if not is_sharding_allowed_for_worker_type(worker_type):
  622. error(
  623. f"There can be only a single worker with {worker_type} "
  624. "type. Please recount and remove."
  625. )
  626. # Not in shard counter, must not have seen it yet, add it.
  627. worker_type_shard_counter[worker_type] += 1
  628. # Generate the number for the worker using incrementing counter
  629. worker_base_name_counter[worker_base_name] += 1
  630. worker_number = worker_base_name_counter[worker_base_name]
  631. worker_name = f"{worker_base_name}{worker_number}"
  632. if worker_number > 1:
  633. # If this isn't the first worker, check that we don't have a confusing
  634. # mixture of worker types with the same base name.
  635. first_worker_with_base_name = dict_to_return[f"{worker_base_name}1"]
  636. if first_worker_with_base_name != worker_types_set:
  637. error(
  638. f"Can not use worker_name: '{worker_name}' for worker_type(s): "
  639. f"{worker_types_set!r}. It is already in use by "
  640. f"worker_type(s): {first_worker_with_base_name!r}"
  641. )
  642. dict_to_return[worker_name] = worker_types_set
  643. return dict_to_return
  644. def generate_worker_files(
  645. environ: Mapping[str, str],
  646. config_path: str,
  647. data_dir: str,
  648. requested_worker_types: Dict[str, Set[str]],
  649. ) -> None:
  650. """Read the desired workers(if any) that is passed in and generate shared
  651. homeserver, nginx and supervisord configs.
  652. Args:
  653. environ: os.environ instance.
  654. config_path: The location of the generated Synapse main worker config file.
  655. data_dir: The location of the synapse data directory. Where log and
  656. user-facing config files live.
  657. requested_worker_types: A Dict containing requested workers in the format of
  658. {'worker_name1': {'worker_type', ...}}
  659. """
  660. # Note that yaml cares about indentation, so care should be taken to insert lines
  661. # into files at the correct indentation below.
  662. # Convenience helper for if using unix sockets instead of host:port
  663. using_unix_sockets = environ.get("SYNAPSE_USE_UNIX_SOCKET", False)
  664. # First read the original config file and extract the listeners block. Then we'll
  665. # add another listener for replication. Later we'll write out the result to the
  666. # shared config file.
  667. listeners: List[Any]
  668. if using_unix_sockets:
  669. listeners = [
  670. {
  671. "path": MAIN_PROCESS_UNIX_SOCKET_PRIVATE_PATH,
  672. "type": "http",
  673. "resources": [{"names": ["replication"]}],
  674. }
  675. ]
  676. else:
  677. listeners = [
  678. {
  679. "port": MAIN_PROCESS_REPLICATION_PORT,
  680. "bind_address": MAIN_PROCESS_LOCALHOST_ADDRESS,
  681. "type": "http",
  682. "resources": [{"names": ["replication"]}],
  683. }
  684. ]
  685. with open(config_path) as file_stream:
  686. original_config = yaml.safe_load(file_stream)
  687. original_listeners = original_config.get("listeners")
  688. if original_listeners:
  689. listeners += original_listeners
  690. # The shared homeserver config. The contents of which will be inserted into the
  691. # base shared worker jinja2 template. This config file will be passed to all
  692. # workers, included Synapse's main process. It is intended mainly for disabling
  693. # functionality when certain workers are spun up, and adding a replication listener.
  694. shared_config: Dict[str, Any] = {"listeners": listeners}
  695. # List of dicts that describe workers.
  696. # We pass this to the Supervisor template later to generate the appropriate
  697. # program blocks.
  698. worker_descriptors: List[Dict[str, Any]] = []
  699. # Upstreams for load-balancing purposes. This dict takes the form of the worker
  700. # type to the ports of each worker. For example:
  701. # {
  702. # worker_type: {1234, 1235, ...}}
  703. # }
  704. # and will be used to construct 'upstream' nginx directives.
  705. nginx_upstreams: Dict[str, Set[int]] = {}
  706. # A map of: {"endpoint": "upstream"}, where "upstream" is a str representing what
  707. # will be placed after the proxy_pass directive. The main benefit to representing
  708. # this data as a dict over a str is that we can easily deduplicate endpoints
  709. # across multiple instances of the same worker. The final rendering will be combined
  710. # with nginx_upstreams and placed in /etc/nginx/conf.d.
  711. nginx_locations: Dict[str, str] = {}
  712. # Create the worker configuration directory if it doesn't already exist
  713. os.makedirs("/conf/workers", exist_ok=True)
  714. # Start worker ports from this arbitrary port
  715. worker_port = 18009
  716. # A list of internal endpoints to healthcheck, starting with the main process
  717. # which exists even if no workers do.
  718. # This list ends up being part of the command line to curl, (curl added support for
  719. # Unix sockets in version 7.40).
  720. if using_unix_sockets:
  721. healthcheck_urls = [
  722. f"--unix-socket {MAIN_PROCESS_UNIX_SOCKET_PUBLIC_PATH} "
  723. # The scheme and hostname from the following URL are ignored.
  724. # The only thing that matters is the path `/health`
  725. "http://localhost/health"
  726. ]
  727. else:
  728. healthcheck_urls = ["http://localhost:8080/health"]
  729. # Get the set of all worker types that we have configured
  730. all_worker_types_in_use = set(chain(*requested_worker_types.values()))
  731. # Map locations to upstreams (corresponding to worker types) in Nginx
  732. # but only if we use the appropriate worker type
  733. for worker_type in all_worker_types_in_use:
  734. for endpoint_pattern in WORKERS_CONFIG[worker_type]["endpoint_patterns"]:
  735. nginx_locations[endpoint_pattern] = f"http://{worker_type}"
  736. # For each worker type specified by the user, create config values and write it's
  737. # yaml config file
  738. for worker_name, worker_types_set in requested_worker_types.items():
  739. # The collected and processed data will live here.
  740. worker_config: Dict[str, Any] = {}
  741. # Merge all worker config templates for this worker into a single config
  742. for worker_type in worker_types_set:
  743. copy_of_template_config = WORKERS_CONFIG[worker_type].copy()
  744. # Merge worker type template configuration data. It's a combination of lists
  745. # and dicts, so use this helper.
  746. worker_config = merge_worker_template_configs(
  747. worker_config, copy_of_template_config
  748. )
  749. # Replace placeholder names in the config template with the actual worker name.
  750. worker_config = insert_worker_name_for_worker_config(worker_config, worker_name)
  751. worker_config.update(
  752. {"name": worker_name, "port": str(worker_port), "config_path": config_path}
  753. )
  754. # Update the shared config with any worker_type specific options. The first of a
  755. # given worker_type needs to stay assigned and not be replaced.
  756. worker_config["shared_extra_conf"].update(shared_config)
  757. shared_config = worker_config["shared_extra_conf"]
  758. if using_unix_sockets:
  759. healthcheck_urls.append(
  760. f"--unix-socket /run/worker.{worker_port} http://localhost/health"
  761. )
  762. else:
  763. healthcheck_urls.append("http://localhost:%d/health" % (worker_port,))
  764. # Update the shared config with sharding-related options if necessary
  765. add_worker_roles_to_shared_config(
  766. shared_config, worker_types_set, worker_name, worker_port
  767. )
  768. # Enable the worker in supervisord
  769. worker_descriptors.append(worker_config)
  770. # Write out the worker's logging config file
  771. log_config_filepath = generate_worker_log_config(environ, worker_name, data_dir)
  772. # Then a worker config file
  773. convert(
  774. "/conf/worker.yaml.j2",
  775. f"/conf/workers/{worker_name}.yaml",
  776. **worker_config,
  777. worker_log_config_filepath=log_config_filepath,
  778. using_unix_sockets=using_unix_sockets,
  779. )
  780. # Save this worker's port number to the correct nginx upstreams
  781. for worker_type in worker_types_set:
  782. nginx_upstreams.setdefault(worker_type, set()).add(worker_port)
  783. worker_port += 1
  784. # Build the nginx location config blocks
  785. nginx_location_config = ""
  786. for endpoint, upstream in nginx_locations.items():
  787. nginx_location_config += NGINX_LOCATION_CONFIG_BLOCK.format(
  788. endpoint=endpoint,
  789. upstream=upstream,
  790. )
  791. # Determine the load-balancing upstreams to configure
  792. nginx_upstream_config = ""
  793. for upstream_worker_base_name, upstream_worker_ports in nginx_upstreams.items():
  794. body = ""
  795. if using_unix_sockets:
  796. for port in upstream_worker_ports:
  797. body += f" server unix:/run/worker.{port};\n"
  798. else:
  799. for port in upstream_worker_ports:
  800. body += f" server localhost:{port};\n"
  801. # Add to the list of configured upstreams
  802. nginx_upstream_config += NGINX_UPSTREAM_CONFIG_BLOCK.format(
  803. upstream_worker_base_name=upstream_worker_base_name,
  804. body=body,
  805. )
  806. # Finally, we'll write out the config files.
  807. # log config for the master process
  808. master_log_config = generate_worker_log_config(environ, "master", data_dir)
  809. shared_config["log_config"] = master_log_config
  810. # Find application service registrations
  811. appservice_registrations = None
  812. appservice_registration_dir = os.environ.get("SYNAPSE_AS_REGISTRATION_DIR")
  813. if appservice_registration_dir:
  814. # Scan for all YAML files that should be application service registrations.
  815. appservice_registrations = [
  816. str(reg_path.resolve())
  817. for reg_path in Path(appservice_registration_dir).iterdir()
  818. if reg_path.suffix.lower() in (".yaml", ".yml")
  819. ]
  820. workers_in_use = len(requested_worker_types) > 0
  821. # If there are workers, add the main process to the instance_map too.
  822. if workers_in_use:
  823. instance_map = shared_config.setdefault("instance_map", {})
  824. if using_unix_sockets:
  825. instance_map[MAIN_PROCESS_INSTANCE_NAME] = {
  826. "path": MAIN_PROCESS_UNIX_SOCKET_PRIVATE_PATH,
  827. }
  828. else:
  829. instance_map[MAIN_PROCESS_INSTANCE_NAME] = {
  830. "host": MAIN_PROCESS_LOCALHOST_ADDRESS,
  831. "port": MAIN_PROCESS_REPLICATION_PORT,
  832. }
  833. # Shared homeserver config
  834. convert(
  835. "/conf/shared.yaml.j2",
  836. "/conf/workers/shared.yaml",
  837. shared_worker_config=yaml.dump(shared_config),
  838. appservice_registrations=appservice_registrations,
  839. enable_redis=workers_in_use,
  840. workers_in_use=workers_in_use,
  841. using_unix_sockets=using_unix_sockets,
  842. )
  843. # Nginx config
  844. convert(
  845. "/conf/nginx.conf.j2",
  846. "/etc/nginx/conf.d/matrix-synapse.conf",
  847. worker_locations=nginx_location_config,
  848. upstream_directives=nginx_upstream_config,
  849. tls_cert_path=os.environ.get("SYNAPSE_TLS_CERT"),
  850. tls_key_path=os.environ.get("SYNAPSE_TLS_KEY"),
  851. using_unix_sockets=using_unix_sockets,
  852. )
  853. # Supervisord config
  854. os.makedirs("/etc/supervisor", exist_ok=True)
  855. convert(
  856. "/conf/supervisord.conf.j2",
  857. "/etc/supervisor/supervisord.conf",
  858. main_config_path=config_path,
  859. enable_redis=workers_in_use,
  860. using_unix_sockets=using_unix_sockets,
  861. )
  862. convert(
  863. "/conf/synapse.supervisord.conf.j2",
  864. "/etc/supervisor/conf.d/synapse.conf",
  865. workers=worker_descriptors,
  866. main_config_path=config_path,
  867. use_forking_launcher=environ.get("SYNAPSE_USE_EXPERIMENTAL_FORKING_LAUNCHER"),
  868. )
  869. # healthcheck config
  870. convert(
  871. "/conf/healthcheck.sh.j2",
  872. "/healthcheck.sh",
  873. healthcheck_urls=healthcheck_urls,
  874. )
  875. # Ensure the logging directory exists
  876. log_dir = data_dir + "/logs"
  877. if not os.path.exists(log_dir):
  878. os.mkdir(log_dir)
  879. def generate_worker_log_config(
  880. environ: Mapping[str, str], worker_name: str, data_dir: str
  881. ) -> str:
  882. """Generate a log.config file for the given worker.
  883. Returns: the path to the generated file
  884. """
  885. # Check whether we should write worker logs to disk, in addition to the console
  886. extra_log_template_args: Dict[str, Optional[str]] = {}
  887. if environ.get("SYNAPSE_WORKERS_WRITE_LOGS_TO_DISK"):
  888. extra_log_template_args["LOG_FILE_PATH"] = f"{data_dir}/logs/{worker_name}.log"
  889. extra_log_template_args["SYNAPSE_LOG_LEVEL"] = environ.get("SYNAPSE_LOG_LEVEL")
  890. extra_log_template_args["SYNAPSE_LOG_SENSITIVE"] = environ.get(
  891. "SYNAPSE_LOG_SENSITIVE"
  892. )
  893. extra_log_template_args["SYNAPSE_LOG_TESTING"] = environ.get("SYNAPSE_LOG_TESTING")
  894. # Render and write the file
  895. log_config_filepath = f"/conf/workers/{worker_name}.log.config"
  896. convert(
  897. "/conf/log.config",
  898. log_config_filepath,
  899. worker_name=worker_name,
  900. **extra_log_template_args,
  901. include_worker_name_in_log_line=environ.get(
  902. "SYNAPSE_USE_EXPERIMENTAL_FORKING_LAUNCHER"
  903. ),
  904. )
  905. return log_config_filepath
  906. def main(args: List[str], environ: MutableMapping[str, str]) -> None:
  907. config_dir = environ.get("SYNAPSE_CONFIG_DIR", "/data")
  908. config_path = environ.get("SYNAPSE_CONFIG_PATH", config_dir + "/homeserver.yaml")
  909. data_dir = environ.get("SYNAPSE_DATA_DIR", "/data")
  910. # override SYNAPSE_NO_TLS, we don't support TLS in worker mode,
  911. # this needs to be handled by a frontend proxy
  912. environ["SYNAPSE_NO_TLS"] = "yes"
  913. # Generate the base homeserver config if one does not yet exist
  914. if not os.path.exists(config_path):
  915. log("Generating base homeserver config")
  916. generate_base_homeserver_config()
  917. else:
  918. log("Base homeserver config exists—not regenerating")
  919. # This script may be run multiple times (mostly by Complement, see note at top of
  920. # file). Don't re-configure workers in this instance.
  921. mark_filepath = "/conf/workers_have_been_configured"
  922. if not os.path.exists(mark_filepath):
  923. # Collect and validate worker_type requests
  924. # Read the desired worker configuration from the environment
  925. worker_types_env = environ.get("SYNAPSE_WORKER_TYPES", "").strip()
  926. # Only process worker_types if they exist
  927. if not worker_types_env:
  928. # No workers, just the main process
  929. worker_types = []
  930. requested_worker_types: Dict[str, Any] = {}
  931. else:
  932. # Split type names by comma, ignoring whitespace.
  933. worker_types = split_and_strip_string(worker_types_env, ",")
  934. requested_worker_types = parse_worker_types(worker_types)
  935. # Always regenerate all other config files
  936. log("Generating worker config files")
  937. generate_worker_files(environ, config_path, data_dir, requested_worker_types)
  938. # Mark workers as being configured
  939. with open(mark_filepath, "w") as f:
  940. f.write("")
  941. else:
  942. log("Worker config exists—not regenerating")
  943. # Lifted right out of start.py
  944. jemallocpath = "/usr/lib/%s-linux-gnu/libjemalloc.so.2" % (platform.machine(),)
  945. if os.path.isfile(jemallocpath):
  946. environ["LD_PRELOAD"] = jemallocpath
  947. else:
  948. log("Could not find %s, will not use" % (jemallocpath,))
  949. # Start supervisord, which will start Synapse, all of the configured worker
  950. # processes, redis, nginx etc. according to the config we created above.
  951. log("Starting supervisord")
  952. flush_buffers()
  953. os.execle(
  954. "/usr/local/bin/supervisord",
  955. "supervisord",
  956. "-c",
  957. "/etc/supervisor/supervisord.conf",
  958. environ,
  959. )
  960. if __name__ == "__main__":
  961. main(sys.argv, os.environ)