1
0

configure_workers_and_start.py 22 KB

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