configure_workers_and_start.py 40 KB

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