1
0

configure_workers_and_start.py 27 KB

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