configure_workers_and_start.py 23 KB

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