configure_workers_and_start.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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 WORKER_CONFIG
  22. # below. Leave empty for no workers.
  23. # * SYNAPSE_AS_REGISTRATION_DIR: If specified, a directory in which .yaml and .yml files
  24. # will be treated as Application Service registration files.
  25. # * SYNAPSE_TLS_CERT: Path to a TLS certificate in PEM format.
  26. # * SYNAPSE_TLS_KEY: Path to a TLS key. If this and SYNAPSE_TLS_CERT are specified,
  27. # Nginx will be configured to serve TLS on port 8448.
  28. # * SYNAPSE_USE_EXPERIMENTAL_FORKING_LAUNCHER: Whether to use the forking launcher,
  29. # only intended for usage in Complement at the moment.
  30. # No stability guarantees are provided.
  31. # * SYNAPSE_LOG_LEVEL: Set this to DEBUG, INFO, WARNING or ERROR to change the
  32. # log level. INFO is the default.
  33. # * SYNAPSE_LOG_SENSITIVE: If unset, SQL and SQL values won't be logged,
  34. # regardless of the SYNAPSE_LOG_LEVEL setting.
  35. #
  36. # NOTE: According to Complement's ENTRYPOINT expectations for a homeserver image (as defined
  37. # in the project's README), this script may be run multiple times, and functionality should
  38. # continue to work if so.
  39. import os
  40. import platform
  41. import subprocess
  42. import sys
  43. from pathlib import Path
  44. from typing import Any, Dict, List, Mapping, MutableMapping, NoReturn, Optional, Set
  45. import yaml
  46. from jinja2 import Environment, FileSystemLoader
  47. MAIN_PROCESS_HTTP_LISTENER_PORT = 8080
  48. # Workers with exposed endpoints needs either "client", "federation", or "media" listener_resources
  49. # Watching /_matrix/client needs a "client" listener
  50. # Watching /_matrix/federation needs a "federation" listener
  51. # Watching /_matrix/media and related needs a "media" listener
  52. # Stream Writers require "client" and "replication" listeners because they
  53. # have to attach by instance_map to the master process and have client endpoints.
  54. WORKERS_CONFIG: Dict[str, Dict[str, Any]] = {
  55. "pusher": {
  56. "app": "synapse.app.generic_worker",
  57. "listener_resources": [],
  58. "endpoint_patterns": [],
  59. "shared_extra_conf": {},
  60. "worker_extra_conf": "",
  61. },
  62. "user_dir": {
  63. "app": "synapse.app.generic_worker",
  64. "listener_resources": ["client"],
  65. "endpoint_patterns": [
  66. "^/_matrix/client/(api/v1|r0|v3|unstable)/user_directory/search$"
  67. ],
  68. "shared_extra_conf": {"update_user_directory_from_worker": "user_dir1"},
  69. "worker_extra_conf": "",
  70. },
  71. "media_repository": {
  72. "app": "synapse.app.media_repository",
  73. "listener_resources": ["media"],
  74. "endpoint_patterns": [
  75. "^/_matrix/media/",
  76. "^/_synapse/admin/v1/purge_media_cache$",
  77. "^/_synapse/admin/v1/room/.*/media.*$",
  78. "^/_synapse/admin/v1/user/.*/media.*$",
  79. "^/_synapse/admin/v1/media/.*$",
  80. "^/_synapse/admin/v1/quarantine_media/.*$",
  81. ],
  82. # The first configured media worker will run the media background jobs
  83. "shared_extra_conf": {
  84. "enable_media_repo": False,
  85. "media_instance_running_background_jobs": "media_repository1",
  86. },
  87. "worker_extra_conf": "enable_media_repo: true",
  88. },
  89. "appservice": {
  90. "app": "synapse.app.generic_worker",
  91. "listener_resources": [],
  92. "endpoint_patterns": [],
  93. "shared_extra_conf": {"notify_appservices_from_worker": "appservice1"},
  94. "worker_extra_conf": "",
  95. },
  96. "federation_sender": {
  97. "app": "synapse.app.generic_worker",
  98. "listener_resources": [],
  99. "endpoint_patterns": [],
  100. "shared_extra_conf": {},
  101. "worker_extra_conf": "",
  102. },
  103. "synchrotron": {
  104. "app": "synapse.app.generic_worker",
  105. "listener_resources": ["client"],
  106. "endpoint_patterns": [
  107. "^/_matrix/client/(v2_alpha|r0|v3)/sync$",
  108. "^/_matrix/client/(api/v1|v2_alpha|r0|v3)/events$",
  109. "^/_matrix/client/(api/v1|r0|v3)/initialSync$",
  110. "^/_matrix/client/(api/v1|r0|v3)/rooms/[^/]+/initialSync$",
  111. ],
  112. "shared_extra_conf": {},
  113. "worker_extra_conf": "",
  114. },
  115. "client_reader": {
  116. "app": "synapse.app.generic_worker",
  117. "listener_resources": ["client"],
  118. "endpoint_patterns": [
  119. "^/_matrix/client/(api/v1|r0|v3|unstable)/publicRooms$",
  120. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/joined_members$",
  121. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/context/.*$",
  122. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/members$",
  123. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state$",
  124. "^/_matrix/client/v1/rooms/.*/hierarchy$",
  125. "^/_matrix/client/(v1|unstable)/rooms/.*/relations/",
  126. "^/_matrix/client/v1/rooms/.*/threads$",
  127. "^/_matrix/client/(api/v1|r0|v3|unstable)/login$",
  128. "^/_matrix/client/(api/v1|r0|v3|unstable)/account/3pid$",
  129. "^/_matrix/client/(api/v1|r0|v3|unstable)/account/whoami$",
  130. "^/_matrix/client/versions$",
  131. "^/_matrix/client/(api/v1|r0|v3|unstable)/voip/turnServer$",
  132. "^/_matrix/client/(r0|v3|unstable)/register$",
  133. "^/_matrix/client/(r0|v3|unstable)/auth/.*/fallback/web$",
  134. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/messages$",
  135. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/event",
  136. "^/_matrix/client/(api/v1|r0|v3|unstable)/joined_rooms",
  137. "^/_matrix/client/(api/v1|r0|v3|unstable/.*)/rooms/.*/aliases",
  138. "^/_matrix/client/(api/v1|r0|v3|unstable)/search",
  139. ],
  140. "shared_extra_conf": {},
  141. "worker_extra_conf": "",
  142. },
  143. "federation_reader": {
  144. "app": "synapse.app.generic_worker",
  145. "listener_resources": ["federation"],
  146. "endpoint_patterns": [
  147. "^/_matrix/federation/(v1|v2)/event/",
  148. "^/_matrix/federation/(v1|v2)/state/",
  149. "^/_matrix/federation/(v1|v2)/state_ids/",
  150. "^/_matrix/federation/(v1|v2)/backfill/",
  151. "^/_matrix/federation/(v1|v2)/get_missing_events/",
  152. "^/_matrix/federation/(v1|v2)/publicRooms",
  153. "^/_matrix/federation/(v1|v2)/query/",
  154. "^/_matrix/federation/(v1|v2)/make_join/",
  155. "^/_matrix/federation/(v1|v2)/make_leave/",
  156. "^/_matrix/federation/(v1|v2)/send_join/",
  157. "^/_matrix/federation/(v1|v2)/send_leave/",
  158. "^/_matrix/federation/(v1|v2)/invite/",
  159. "^/_matrix/federation/(v1|v2)/query_auth/",
  160. "^/_matrix/federation/(v1|v2)/event_auth/",
  161. "^/_matrix/federation/(v1|v2)/exchange_third_party_invite/",
  162. "^/_matrix/federation/(v1|v2)/user/devices/",
  163. "^/_matrix/federation/(v1|v2)/get_groups_publicised$",
  164. "^/_matrix/key/v2/query",
  165. ],
  166. "shared_extra_conf": {},
  167. "worker_extra_conf": "",
  168. },
  169. "federation_inbound": {
  170. "app": "synapse.app.generic_worker",
  171. "listener_resources": ["federation"],
  172. "endpoint_patterns": ["/_matrix/federation/(v1|v2)/send/"],
  173. "shared_extra_conf": {},
  174. "worker_extra_conf": "",
  175. },
  176. "event_persister": {
  177. "app": "synapse.app.generic_worker",
  178. "listener_resources": ["replication"],
  179. "endpoint_patterns": [],
  180. "shared_extra_conf": {},
  181. "worker_extra_conf": "",
  182. },
  183. "background_worker": {
  184. "app": "synapse.app.generic_worker",
  185. "listener_resources": [],
  186. "endpoint_patterns": [],
  187. # This worker cannot be sharded. Therefore there should only ever be one background
  188. # worker, and it should be named background_worker1
  189. "shared_extra_conf": {"run_background_tasks_on": "background_worker1"},
  190. "worker_extra_conf": "",
  191. },
  192. "event_creator": {
  193. "app": "synapse.app.generic_worker",
  194. "listener_resources": ["client"],
  195. "endpoint_patterns": [
  196. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/redact",
  197. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/send",
  198. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/(join|invite|leave|ban|unban|kick)$",
  199. "^/_matrix/client/(api/v1|r0|v3|unstable)/join/",
  200. "^/_matrix/client/(api/v1|r0|v3|unstable)/profile/",
  201. "^/_matrix/client/(v1|unstable/org.matrix.msc2716)/rooms/.*/batch_send",
  202. ],
  203. "shared_extra_conf": {},
  204. "worker_extra_conf": "",
  205. },
  206. "frontend_proxy": {
  207. "app": "synapse.app.generic_worker",
  208. "listener_resources": ["client", "replication"],
  209. "endpoint_patterns": ["^/_matrix/client/(api/v1|r0|v3|unstable)/keys/upload"],
  210. "shared_extra_conf": {},
  211. "worker_extra_conf": "",
  212. },
  213. "account_data": {
  214. "app": "synapse.app.generic_worker",
  215. "listener_resources": ["client", "replication"],
  216. "endpoint_patterns": [
  217. "^/_matrix/client/(r0|v3|unstable)/.*/tags",
  218. "^/_matrix/client/(r0|v3|unstable)/.*/account_data",
  219. ],
  220. "shared_extra_conf": {},
  221. "worker_extra_conf": "",
  222. },
  223. "presence": {
  224. "app": "synapse.app.generic_worker",
  225. "listener_resources": ["client", "replication"],
  226. "endpoint_patterns": ["^/_matrix/client/(api/v1|r0|v3|unstable)/presence/"],
  227. "shared_extra_conf": {},
  228. "worker_extra_conf": "",
  229. },
  230. "receipts": {
  231. "app": "synapse.app.generic_worker",
  232. "listener_resources": ["client", "replication"],
  233. "endpoint_patterns": [
  234. "^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt",
  235. "^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers",
  236. ],
  237. "shared_extra_conf": {},
  238. "worker_extra_conf": "",
  239. },
  240. "to_device": {
  241. "app": "synapse.app.generic_worker",
  242. "listener_resources": ["client", "replication"],
  243. "endpoint_patterns": ["^/_matrix/client/(r0|v3|unstable)/sendToDevice/"],
  244. "shared_extra_conf": {},
  245. "worker_extra_conf": "",
  246. },
  247. "typing": {
  248. "app": "synapse.app.generic_worker",
  249. "listener_resources": ["client", "replication"],
  250. "endpoint_patterns": [
  251. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/typing"
  252. ],
  253. "shared_extra_conf": {},
  254. "worker_extra_conf": "",
  255. },
  256. }
  257. # Templates for sections that may be inserted multiple times in config files
  258. NGINX_LOCATION_CONFIG_BLOCK = """
  259. location ~* {endpoint} {{
  260. proxy_pass {upstream};
  261. proxy_set_header X-Forwarded-For $remote_addr;
  262. proxy_set_header X-Forwarded-Proto $scheme;
  263. proxy_set_header Host $host;
  264. }}
  265. """
  266. NGINX_UPSTREAM_CONFIG_BLOCK = """
  267. upstream {upstream_worker_type} {{
  268. {body}
  269. }}
  270. """
  271. # Utility functions
  272. def log(txt: str) -> None:
  273. print(txt)
  274. def error(txt: str) -> NoReturn:
  275. print(txt, file=sys.stderr)
  276. sys.exit(2)
  277. def flush_buffers() -> None:
  278. sys.stdout.flush()
  279. sys.stderr.flush()
  280. def convert(src: str, dst: str, **template_vars: object) -> None:
  281. """Generate a file from a template
  282. Args:
  283. src: Path to the input file.
  284. dst: Path to write to.
  285. template_vars: The arguments to replace placeholder variables in the template with.
  286. """
  287. # Read the template file
  288. # We disable autoescape to prevent template variables from being escaped,
  289. # as we're not using HTML.
  290. env = Environment(loader=FileSystemLoader(os.path.dirname(src)), autoescape=False)
  291. template = env.get_template(os.path.basename(src))
  292. # Generate a string from the template.
  293. rendered = template.render(**template_vars)
  294. # Write the generated contents to a file
  295. #
  296. # We use append mode in case the files have already been written to by something else
  297. # (for instance, as part of the instructions in a dockerfile).
  298. with open(dst, "a") as outfile:
  299. # In case the existing file doesn't end with a newline
  300. outfile.write("\n")
  301. outfile.write(rendered)
  302. def add_worker_roles_to_shared_config(
  303. shared_config: dict,
  304. worker_type: str,
  305. worker_name: str,
  306. worker_port: int,
  307. ) -> None:
  308. """Given a dictionary representing a config file shared across all workers,
  309. append appropriate worker information to it for the current worker_type instance.
  310. Args:
  311. shared_config: The config dict that all worker instances share (after being converted to YAML)
  312. worker_type: The type of worker (one of those defined in WORKERS_CONFIG).
  313. worker_name: The name of the worker instance.
  314. worker_port: The HTTP replication port that the worker instance is listening on.
  315. """
  316. # The instance_map config field marks the workers that write to various replication streams
  317. instance_map = shared_config.setdefault("instance_map", {})
  318. # Worker-type specific sharding config
  319. if worker_type == "pusher":
  320. shared_config.setdefault("pusher_instances", []).append(worker_name)
  321. elif worker_type == "federation_sender":
  322. shared_config.setdefault("federation_sender_instances", []).append(worker_name)
  323. elif worker_type == "event_persister":
  324. # Event persisters write to the events stream, so we need to update
  325. # the list of event stream writers
  326. shared_config.setdefault("stream_writers", {}).setdefault("events", []).append(
  327. worker_name
  328. )
  329. # Map of stream writer instance names to host/ports combos
  330. instance_map[worker_name] = {
  331. "host": "localhost",
  332. "port": worker_port,
  333. }
  334. elif worker_type in ["account_data", "presence", "receipts", "to_device", "typing"]:
  335. # Update the list of stream writers
  336. # It's convenient that the name of the worker type is the same as the stream to write
  337. shared_config.setdefault("stream_writers", {}).setdefault(
  338. worker_type, []
  339. ).append(worker_name)
  340. # Map of stream writer instance names to host/ports combos
  341. # For now, all stream writers need http replication ports
  342. instance_map[worker_name] = {
  343. "host": "localhost",
  344. "port": worker_port,
  345. }
  346. def generate_base_homeserver_config() -> None:
  347. """Starts Synapse and generates a basic homeserver config, which will later be
  348. modified for worker support.
  349. Raises: CalledProcessError if calling start.py returned a non-zero exit code.
  350. """
  351. # start.py already does this for us, so just call that.
  352. # note that this script is copied in in the official, monolith dockerfile
  353. os.environ["SYNAPSE_HTTP_PORT"] = str(MAIN_PROCESS_HTTP_LISTENER_PORT)
  354. subprocess.run(["/usr/local/bin/python", "/start.py", "migrate_config"], check=True)
  355. def generate_worker_files(
  356. environ: Mapping[str, str], config_path: str, data_dir: str
  357. ) -> None:
  358. """Read the desired list of workers from environment variables and generate
  359. shared homeserver, nginx and supervisord configs.
  360. Args:
  361. environ: os.environ instance.
  362. config_path: The location of the generated Synapse main worker config file.
  363. data_dir: The location of the synapse data directory. Where log and
  364. user-facing config files live.
  365. """
  366. # Note that yaml cares about indentation, so care should be taken to insert lines
  367. # into files at the correct indentation below.
  368. # shared_config is the contents of a Synapse config file that will be shared amongst
  369. # the main Synapse process as well as all workers.
  370. # It is intended mainly for disabling functionality when certain workers are spun up,
  371. # and adding a replication listener.
  372. # First read the original config file and extract the listeners block. Then we'll add
  373. # another listener for replication. Later we'll write out the result to the shared
  374. # config file.
  375. listeners = [
  376. {
  377. "port": 9093,
  378. "bind_address": "127.0.0.1",
  379. "type": "http",
  380. "resources": [{"names": ["replication"]}],
  381. }
  382. ]
  383. with open(config_path) as file_stream:
  384. original_config = yaml.safe_load(file_stream)
  385. original_listeners = original_config.get("listeners")
  386. if original_listeners:
  387. listeners += original_listeners
  388. # The shared homeserver config. The contents of which will be inserted into the
  389. # base shared worker jinja2 template.
  390. #
  391. # This config file will be passed to all workers, included Synapse's main process.
  392. shared_config: Dict[str, Any] = {"listeners": listeners}
  393. # List of dicts that describe workers.
  394. # We pass this to the Supervisor template later to generate the appropriate
  395. # program blocks.
  396. worker_descriptors: List[Dict[str, Any]] = []
  397. # Upstreams for load-balancing purposes. This dict takes the form of a worker type to the
  398. # ports of each worker. For example:
  399. # {
  400. # worker_type: {1234, 1235, ...}}
  401. # }
  402. # and will be used to construct 'upstream' nginx directives.
  403. nginx_upstreams: Dict[str, Set[int]] = {}
  404. # A map of: {"endpoint": "upstream"}, where "upstream" is a str representing what will be
  405. # placed after the proxy_pass directive. The main benefit to representing this data as a
  406. # dict over a str is that we can easily deduplicate endpoints across multiple instances
  407. # of the same worker.
  408. #
  409. # An nginx site config that will be amended to depending on the workers that are
  410. # spun up. To be placed in /etc/nginx/conf.d.
  411. nginx_locations = {}
  412. # Read the desired worker configuration from the environment
  413. worker_types_env = environ.get("SYNAPSE_WORKER_TYPES", "").strip()
  414. if not worker_types_env:
  415. # No workers, just the main process
  416. worker_types = []
  417. else:
  418. # Split type names by comma, ignoring whitespace.
  419. worker_types = [x.strip() for x in worker_types_env.split(",")]
  420. # Create the worker configuration directory if it doesn't already exist
  421. os.makedirs("/conf/workers", exist_ok=True)
  422. # Start worker ports from this arbitrary port
  423. worker_port = 18009
  424. # A counter of worker_type -> int. Used for determining the name for a given
  425. # worker type when generating its config file, as each worker's name is just
  426. # worker_type + instance #
  427. worker_type_counter: Dict[str, int] = {}
  428. # A list of internal endpoints to healthcheck, starting with the main process
  429. # which exists even if no workers do.
  430. healthcheck_urls = ["http://localhost:8080/health"]
  431. # For each worker type specified by the user, create config values
  432. for worker_type in worker_types:
  433. worker_config = WORKERS_CONFIG.get(worker_type)
  434. if worker_config:
  435. worker_config = worker_config.copy()
  436. else:
  437. error(worker_type + " is an unknown worker type! Please fix!")
  438. new_worker_count = worker_type_counter.setdefault(worker_type, 0) + 1
  439. worker_type_counter[worker_type] = new_worker_count
  440. # Name workers by their type concatenated with an incrementing number
  441. # e.g. federation_reader1
  442. worker_name = worker_type + str(new_worker_count)
  443. worker_config.update(
  444. {"name": worker_name, "port": str(worker_port), "config_path": config_path}
  445. )
  446. # Update the shared config with any worker-type specific options
  447. shared_config.update(worker_config["shared_extra_conf"])
  448. healthcheck_urls.append("http://localhost:%d/health" % (worker_port,))
  449. # Check if more than one instance of this worker type has been specified
  450. worker_type_total_count = worker_types.count(worker_type)
  451. # Update the shared config with sharding-related options if necessary
  452. add_worker_roles_to_shared_config(
  453. shared_config, worker_type, worker_name, worker_port
  454. )
  455. # Enable the worker in supervisord
  456. worker_descriptors.append(worker_config)
  457. # Add nginx location blocks for this worker's endpoints (if any are defined)
  458. for pattern in worker_config["endpoint_patterns"]:
  459. # Determine whether we need to load-balance this worker
  460. if worker_type_total_count > 1:
  461. # Create or add to a load-balanced upstream for this worker
  462. nginx_upstreams.setdefault(worker_type, set()).add(worker_port)
  463. # Upstreams are named after the worker_type
  464. upstream = "http://" + worker_type
  465. else:
  466. upstream = "http://localhost:%d" % (worker_port,)
  467. # Note that this endpoint should proxy to this upstream
  468. nginx_locations[pattern] = upstream
  469. # Write out the worker's logging config file
  470. log_config_filepath = generate_worker_log_config(environ, worker_name, data_dir)
  471. # Then a worker config file
  472. convert(
  473. "/conf/worker.yaml.j2",
  474. "/conf/workers/{name}.yaml".format(name=worker_name),
  475. **worker_config,
  476. worker_log_config_filepath=log_config_filepath,
  477. )
  478. worker_port += 1
  479. # Build the nginx location config blocks
  480. nginx_location_config = ""
  481. for endpoint, upstream in nginx_locations.items():
  482. nginx_location_config += NGINX_LOCATION_CONFIG_BLOCK.format(
  483. endpoint=endpoint,
  484. upstream=upstream,
  485. )
  486. # Determine the load-balancing upstreams to configure
  487. nginx_upstream_config = ""
  488. for upstream_worker_type, upstream_worker_ports in nginx_upstreams.items():
  489. body = ""
  490. for port in upstream_worker_ports:
  491. body += " server localhost:%d;\n" % (port,)
  492. # Add to the list of configured upstreams
  493. nginx_upstream_config += NGINX_UPSTREAM_CONFIG_BLOCK.format(
  494. upstream_worker_type=upstream_worker_type,
  495. body=body,
  496. )
  497. # Finally, we'll write out the config files.
  498. # log config for the master process
  499. master_log_config = generate_worker_log_config(environ, "master", data_dir)
  500. shared_config["log_config"] = master_log_config
  501. # Find application service registrations
  502. appservice_registrations = None
  503. appservice_registration_dir = os.environ.get("SYNAPSE_AS_REGISTRATION_DIR")
  504. if appservice_registration_dir:
  505. # Scan for all YAML files that should be application service registrations.
  506. appservice_registrations = [
  507. str(reg_path.resolve())
  508. for reg_path in Path(appservice_registration_dir).iterdir()
  509. if reg_path.suffix.lower() in (".yaml", ".yml")
  510. ]
  511. workers_in_use = len(worker_types) > 0
  512. # Shared homeserver config
  513. convert(
  514. "/conf/shared.yaml.j2",
  515. "/conf/workers/shared.yaml",
  516. shared_worker_config=yaml.dump(shared_config),
  517. appservice_registrations=appservice_registrations,
  518. enable_redis=workers_in_use,
  519. workers_in_use=workers_in_use,
  520. )
  521. # Nginx config
  522. convert(
  523. "/conf/nginx.conf.j2",
  524. "/etc/nginx/conf.d/matrix-synapse.conf",
  525. worker_locations=nginx_location_config,
  526. upstream_directives=nginx_upstream_config,
  527. tls_cert_path=os.environ.get("SYNAPSE_TLS_CERT"),
  528. tls_key_path=os.environ.get("SYNAPSE_TLS_KEY"),
  529. )
  530. # Supervisord config
  531. os.makedirs("/etc/supervisor", exist_ok=True)
  532. convert(
  533. "/conf/supervisord.conf.j2",
  534. "/etc/supervisor/supervisord.conf",
  535. main_config_path=config_path,
  536. enable_redis=workers_in_use,
  537. )
  538. convert(
  539. "/conf/synapse.supervisord.conf.j2",
  540. "/etc/supervisor/conf.d/synapse.conf",
  541. workers=worker_descriptors,
  542. main_config_path=config_path,
  543. use_forking_launcher=environ.get("SYNAPSE_USE_EXPERIMENTAL_FORKING_LAUNCHER"),
  544. )
  545. # healthcheck config
  546. convert(
  547. "/conf/healthcheck.sh.j2",
  548. "/healthcheck.sh",
  549. healthcheck_urls=healthcheck_urls,
  550. )
  551. # Ensure the logging directory exists
  552. log_dir = data_dir + "/logs"
  553. if not os.path.exists(log_dir):
  554. os.mkdir(log_dir)
  555. def generate_worker_log_config(
  556. environ: Mapping[str, str], worker_name: str, data_dir: str
  557. ) -> str:
  558. """Generate a log.config file for the given worker.
  559. Returns: the path to the generated file
  560. """
  561. # Check whether we should write worker logs to disk, in addition to the console
  562. extra_log_template_args: Dict[str, Optional[str]] = {}
  563. if environ.get("SYNAPSE_WORKERS_WRITE_LOGS_TO_DISK"):
  564. extra_log_template_args["LOG_FILE_PATH"] = f"{data_dir}/logs/{worker_name}.log"
  565. extra_log_template_args["SYNAPSE_LOG_LEVEL"] = environ.get("SYNAPSE_LOG_LEVEL")
  566. extra_log_template_args["SYNAPSE_LOG_SENSITIVE"] = environ.get(
  567. "SYNAPSE_LOG_SENSITIVE"
  568. )
  569. # Render and write the file
  570. log_config_filepath = f"/conf/workers/{worker_name}.log.config"
  571. convert(
  572. "/conf/log.config",
  573. log_config_filepath,
  574. worker_name=worker_name,
  575. **extra_log_template_args,
  576. include_worker_name_in_log_line=environ.get(
  577. "SYNAPSE_USE_EXPERIMENTAL_FORKING_LAUNCHER"
  578. ),
  579. )
  580. return log_config_filepath
  581. def main(args: List[str], environ: MutableMapping[str, str]) -> None:
  582. config_dir = environ.get("SYNAPSE_CONFIG_DIR", "/data")
  583. config_path = environ.get("SYNAPSE_CONFIG_PATH", config_dir + "/homeserver.yaml")
  584. data_dir = environ.get("SYNAPSE_DATA_DIR", "/data")
  585. # override SYNAPSE_NO_TLS, we don't support TLS in worker mode,
  586. # this needs to be handled by a frontend proxy
  587. environ["SYNAPSE_NO_TLS"] = "yes"
  588. # Generate the base homeserver config if one does not yet exist
  589. if not os.path.exists(config_path):
  590. log("Generating base homeserver config")
  591. generate_base_homeserver_config()
  592. # This script may be run multiple times (mostly by Complement, see note at top of file).
  593. # Don't re-configure workers in this instance.
  594. mark_filepath = "/conf/workers_have_been_configured"
  595. if not os.path.exists(mark_filepath):
  596. # Always regenerate all other config files
  597. generate_worker_files(environ, config_path, data_dir)
  598. # Mark workers as being configured
  599. with open(mark_filepath, "w") as f:
  600. f.write("")
  601. # Lifted right out of start.py
  602. jemallocpath = "/usr/lib/%s-linux-gnu/libjemalloc.so.2" % (platform.machine(),)
  603. if os.path.isfile(jemallocpath):
  604. environ["LD_PRELOAD"] = jemallocpath
  605. else:
  606. log("Could not find %s, will not use" % (jemallocpath,))
  607. # Start supervisord, which will start Synapse, all of the configured worker
  608. # processes, redis, nginx etc. according to the config we created above.
  609. log("Starting supervisord")
  610. flush_buffers()
  611. os.execle(
  612. "/usr/local/bin/supervisord",
  613. "supervisord",
  614. "-c",
  615. "/etc/supervisor/supervisord.conf",
  616. environ,
  617. )
  618. if __name__ == "__main__":
  619. main(sys.argv, os.environ)