configure_workers_and_start.py 40 KB

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