configure_workers_and_start.py 23 KB

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