configure_workers_and_start.py 42 KB

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