configure_workers_and_start.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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 WORKERS_CONFIG
  22. # below. Leave empty for no workers. Add a ':' and a number at the end to
  23. # multiply that worker. Append multiple worker types with '+' to merge the
  24. # worker types into a single worker. Add a name and a '=' to the front of a
  25. # worker type to give this instance a name in logs and nginx.
  26. # Examples:
  27. # SYNAPSE_WORKER_TYPES='event_persister, federation_sender, client_reader'
  28. # SYNAPSE_WORKER_TYPES='event_persister:2, federation_sender:2, client_reader'
  29. # SYNAPSE_WORKER_TYPES='stream_writers=account_data+presence+typing'
  30. # * SYNAPSE_AS_REGISTRATION_DIR: If specified, a directory in which .yaml and .yml files
  31. # will be treated as Application Service registration files.
  32. # * SYNAPSE_TLS_CERT: Path to a TLS certificate in PEM format.
  33. # * SYNAPSE_TLS_KEY: Path to a TLS key. If this and SYNAPSE_TLS_CERT are specified,
  34. # Nginx will be configured to serve TLS on port 8448.
  35. # * SYNAPSE_USE_EXPERIMENTAL_FORKING_LAUNCHER: Whether to use the forking launcher,
  36. # only intended for usage in Complement at the moment.
  37. # No stability guarantees are provided.
  38. # * SYNAPSE_LOG_LEVEL: Set this to DEBUG, INFO, WARNING or ERROR to change the
  39. # log level. INFO is the default.
  40. # * SYNAPSE_LOG_SENSITIVE: If unset, SQL and SQL values won't be logged,
  41. # regardless of the SYNAPSE_LOG_LEVEL setting.
  42. #
  43. # NOTE: According to Complement's ENTRYPOINT expectations for a homeserver image (as defined
  44. # in the project's README), this script may be run multiple times, and functionality should
  45. # continue to work if so.
  46. import os
  47. import platform
  48. import re
  49. import subprocess
  50. import sys
  51. from collections import defaultdict
  52. from itertools import chain
  53. from pathlib import Path
  54. from typing import (
  55. Any,
  56. Dict,
  57. List,
  58. Mapping,
  59. MutableMapping,
  60. NoReturn,
  61. Optional,
  62. Set,
  63. SupportsIndex,
  64. )
  65. import yaml
  66. from jinja2 import Environment, FileSystemLoader
  67. MAIN_PROCESS_HTTP_LISTENER_PORT = 8080
  68. MAIN_PROCESS_INSTANCE_NAME = "main"
  69. MAIN_PROCESS_LOCALHOST_ADDRESS = "127.0.0.1"
  70. MAIN_PROCESS_REPLICATION_PORT = 9093
  71. # A simple name used as a placeholder in the WORKERS_CONFIG below. This will be replaced
  72. # during processing with the name of the worker.
  73. WORKER_PLACEHOLDER_NAME = "placeholder_name"
  74. # Workers with exposed endpoints needs either "client", "federation", or "media" listener_resources
  75. # Watching /_matrix/client needs a "client" listener
  76. # Watching /_matrix/federation needs a "federation" listener
  77. # Watching /_matrix/media and related needs a "media" listener
  78. # Stream Writers require "client" and "replication" listeners because they
  79. # have to attach by instance_map to the master process and have client endpoints.
  80. WORKERS_CONFIG: Dict[str, Dict[str, Any]] = {
  81. "pusher": {
  82. "app": "synapse.app.generic_worker",
  83. "listener_resources": [],
  84. "endpoint_patterns": [],
  85. "shared_extra_conf": {},
  86. "worker_extra_conf": "",
  87. },
  88. "user_dir": {
  89. "app": "synapse.app.generic_worker",
  90. "listener_resources": ["client"],
  91. "endpoint_patterns": [
  92. "^/_matrix/client/(api/v1|r0|v3|unstable)/user_directory/search$"
  93. ],
  94. "shared_extra_conf": {
  95. "update_user_directory_from_worker": WORKER_PLACEHOLDER_NAME
  96. },
  97. "worker_extra_conf": "",
  98. },
  99. "media_repository": {
  100. "app": "synapse.app.generic_worker",
  101. "listener_resources": ["media"],
  102. "endpoint_patterns": [
  103. "^/_matrix/media/",
  104. "^/_synapse/admin/v1/purge_media_cache$",
  105. "^/_synapse/admin/v1/room/.*/media.*$",
  106. "^/_synapse/admin/v1/user/.*/media.*$",
  107. "^/_synapse/admin/v1/media/.*$",
  108. "^/_synapse/admin/v1/quarantine_media/.*$",
  109. ],
  110. # The first configured media worker will run the media background jobs
  111. "shared_extra_conf": {
  112. "enable_media_repo": False,
  113. "media_instance_running_background_jobs": WORKER_PLACEHOLDER_NAME,
  114. },
  115. "worker_extra_conf": "enable_media_repo: true",
  116. },
  117. "appservice": {
  118. "app": "synapse.app.generic_worker",
  119. "listener_resources": [],
  120. "endpoint_patterns": [],
  121. "shared_extra_conf": {
  122. "notify_appservices_from_worker": WORKER_PLACEHOLDER_NAME
  123. },
  124. "worker_extra_conf": "",
  125. },
  126. "federation_sender": {
  127. "app": "synapse.app.generic_worker",
  128. "listener_resources": [],
  129. "endpoint_patterns": [],
  130. "shared_extra_conf": {},
  131. "worker_extra_conf": "",
  132. },
  133. "synchrotron": {
  134. "app": "synapse.app.generic_worker",
  135. "listener_resources": ["client"],
  136. "endpoint_patterns": [
  137. "^/_matrix/client/(v2_alpha|r0|v3)/sync$",
  138. "^/_matrix/client/(api/v1|v2_alpha|r0|v3)/events$",
  139. "^/_matrix/client/(api/v1|r0|v3)/initialSync$",
  140. "^/_matrix/client/(api/v1|r0|v3)/rooms/[^/]+/initialSync$",
  141. ],
  142. "shared_extra_conf": {},
  143. "worker_extra_conf": "",
  144. },
  145. "client_reader": {
  146. "app": "synapse.app.generic_worker",
  147. "listener_resources": ["client"],
  148. "endpoint_patterns": [
  149. "^/_matrix/client/(api/v1|r0|v3|unstable)/publicRooms$",
  150. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/joined_members$",
  151. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/context/.*$",
  152. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/members$",
  153. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state$",
  154. "^/_matrix/client/v1/rooms/.*/hierarchy$",
  155. "^/_matrix/client/(v1|unstable)/rooms/.*/relations/",
  156. "^/_matrix/client/v1/rooms/.*/threads$",
  157. "^/_matrix/client/(api/v1|r0|v3|unstable)/login$",
  158. "^/_matrix/client/(api/v1|r0|v3|unstable)/account/3pid$",
  159. "^/_matrix/client/(api/v1|r0|v3|unstable)/account/whoami$",
  160. "^/_matrix/client/versions$",
  161. "^/_matrix/client/(api/v1|r0|v3|unstable)/voip/turnServer$",
  162. "^/_matrix/client/(r0|v3|unstable)/register$",
  163. "^/_matrix/client/(r0|v3|unstable)/register/available$",
  164. "^/_matrix/client/(r0|v3|unstable)/auth/.*/fallback/web$",
  165. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/messages$",
  166. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/event",
  167. "^/_matrix/client/(api/v1|r0|v3|unstable)/joined_rooms",
  168. "^/_matrix/client/(api/v1|r0|v3|unstable/.*)/rooms/.*/aliases",
  169. "^/_matrix/client/v1/rooms/.*/timestamp_to_event$",
  170. "^/_matrix/client/(api/v1|r0|v3|unstable)/search",
  171. "^/_matrix/client/(r0|v3|unstable)/user/.*/filter(/|$)",
  172. "^/_matrix/client/(r0|v3|unstable)/password_policy$",
  173. "^/_matrix/client/(api/v1|r0|v3|unstable)/directory/room/.*$",
  174. "^/_matrix/client/(r0|v3|unstable)/capabilities$",
  175. ],
  176. "shared_extra_conf": {},
  177. "worker_extra_conf": "",
  178. },
  179. "federation_reader": {
  180. "app": "synapse.app.generic_worker",
  181. "listener_resources": ["federation"],
  182. "endpoint_patterns": [
  183. "^/_matrix/federation/(v1|v2)/event/",
  184. "^/_matrix/federation/(v1|v2)/state/",
  185. "^/_matrix/federation/(v1|v2)/state_ids/",
  186. "^/_matrix/federation/(v1|v2)/backfill/",
  187. "^/_matrix/federation/(v1|v2)/get_missing_events/",
  188. "^/_matrix/federation/(v1|v2)/publicRooms",
  189. "^/_matrix/federation/(v1|v2)/query/",
  190. "^/_matrix/federation/(v1|v2)/make_join/",
  191. "^/_matrix/federation/(v1|v2)/make_leave/",
  192. "^/_matrix/federation/(v1|v2)/send_join/",
  193. "^/_matrix/federation/(v1|v2)/send_leave/",
  194. "^/_matrix/federation/(v1|v2)/invite/",
  195. "^/_matrix/federation/(v1|v2)/query_auth/",
  196. "^/_matrix/federation/(v1|v2)/event_auth/",
  197. "^/_matrix/federation/v1/timestamp_to_event/",
  198. "^/_matrix/federation/(v1|v2)/exchange_third_party_invite/",
  199. "^/_matrix/federation/(v1|v2)/user/devices/",
  200. "^/_matrix/federation/(v1|v2)/get_groups_publicised$",
  201. "^/_matrix/key/v2/query",
  202. ],
  203. "shared_extra_conf": {},
  204. "worker_extra_conf": "",
  205. },
  206. "federation_inbound": {
  207. "app": "synapse.app.generic_worker",
  208. "listener_resources": ["federation"],
  209. "endpoint_patterns": ["/_matrix/federation/(v1|v2)/send/"],
  210. "shared_extra_conf": {},
  211. "worker_extra_conf": "",
  212. },
  213. "event_persister": {
  214. "app": "synapse.app.generic_worker",
  215. "listener_resources": ["replication"],
  216. "endpoint_patterns": [],
  217. "shared_extra_conf": {},
  218. "worker_extra_conf": "",
  219. },
  220. "background_worker": {
  221. "app": "synapse.app.generic_worker",
  222. "listener_resources": [],
  223. "endpoint_patterns": [],
  224. # This worker cannot be sharded. Therefore, there should only ever be one
  225. # background worker. This is enforced for the safety of your database.
  226. "shared_extra_conf": {"run_background_tasks_on": WORKER_PLACEHOLDER_NAME},
  227. "worker_extra_conf": "",
  228. },
  229. "event_creator": {
  230. "app": "synapse.app.generic_worker",
  231. "listener_resources": ["client"],
  232. "endpoint_patterns": [
  233. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/redact",
  234. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/send",
  235. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/(join|invite|leave|ban|unban|kick)$",
  236. "^/_matrix/client/(api/v1|r0|v3|unstable)/join/",
  237. "^/_matrix/client/(api/v1|r0|v3|unstable)/knock/",
  238. "^/_matrix/client/(api/v1|r0|v3|unstable)/profile/",
  239. "^/_matrix/client/(v1|unstable/org.matrix.msc2716)/rooms/.*/batch_send",
  240. ],
  241. "shared_extra_conf": {},
  242. "worker_extra_conf": "",
  243. },
  244. "frontend_proxy": {
  245. "app": "synapse.app.generic_worker",
  246. "listener_resources": ["client", "replication"],
  247. "endpoint_patterns": ["^/_matrix/client/(api/v1|r0|v3|unstable)/keys/upload"],
  248. "shared_extra_conf": {},
  249. "worker_extra_conf": "",
  250. },
  251. "account_data": {
  252. "app": "synapse.app.generic_worker",
  253. "listener_resources": ["client", "replication"],
  254. "endpoint_patterns": [
  255. "^/_matrix/client/(r0|v3|unstable)/.*/tags",
  256. "^/_matrix/client/(r0|v3|unstable)/.*/account_data",
  257. ],
  258. "shared_extra_conf": {},
  259. "worker_extra_conf": "",
  260. },
  261. "presence": {
  262. "app": "synapse.app.generic_worker",
  263. "listener_resources": ["client", "replication"],
  264. "endpoint_patterns": ["^/_matrix/client/(api/v1|r0|v3|unstable)/presence/"],
  265. "shared_extra_conf": {},
  266. "worker_extra_conf": "",
  267. },
  268. "receipts": {
  269. "app": "synapse.app.generic_worker",
  270. "listener_resources": ["client", "replication"],
  271. "endpoint_patterns": [
  272. "^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt",
  273. "^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers",
  274. ],
  275. "shared_extra_conf": {},
  276. "worker_extra_conf": "",
  277. },
  278. "to_device": {
  279. "app": "synapse.app.generic_worker",
  280. "listener_resources": ["client", "replication"],
  281. "endpoint_patterns": ["^/_matrix/client/(r0|v3|unstable)/sendToDevice/"],
  282. "shared_extra_conf": {},
  283. "worker_extra_conf": "",
  284. },
  285. "typing": {
  286. "app": "synapse.app.generic_worker",
  287. "listener_resources": ["client", "replication"],
  288. "endpoint_patterns": [
  289. "^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/typing"
  290. ],
  291. "shared_extra_conf": {},
  292. "worker_extra_conf": "",
  293. },
  294. }
  295. # Templates for sections that may be inserted multiple times in config files
  296. NGINX_LOCATION_CONFIG_BLOCK = """
  297. location ~* {endpoint} {{
  298. proxy_pass {upstream};
  299. proxy_set_header X-Forwarded-For $remote_addr;
  300. proxy_set_header X-Forwarded-Proto $scheme;
  301. proxy_set_header Host $host;
  302. }}
  303. """
  304. NGINX_UPSTREAM_CONFIG_BLOCK = """
  305. upstream {upstream_worker_base_name} {{
  306. {body}
  307. }}
  308. """
  309. # Utility functions
  310. def log(txt: str) -> None:
  311. print(txt)
  312. def error(txt: str) -> NoReturn:
  313. print(txt, file=sys.stderr)
  314. sys.exit(2)
  315. def flush_buffers() -> None:
  316. sys.stdout.flush()
  317. sys.stderr.flush()
  318. def convert(src: str, dst: str, **template_vars: object) -> None:
  319. """Generate a file from a template
  320. Args:
  321. src: Path to the input file.
  322. dst: Path to write to.
  323. template_vars: The arguments to replace placeholder variables in the template with.
  324. """
  325. # Read the template file
  326. # We disable autoescape to prevent template variables from being escaped,
  327. # as we're not using HTML.
  328. env = Environment(loader=FileSystemLoader(os.path.dirname(src)), autoescape=False)
  329. template = env.get_template(os.path.basename(src))
  330. # Generate a string from the template.
  331. rendered = template.render(**template_vars)
  332. # Write the generated contents to a file
  333. #
  334. # We use append mode in case the files have already been written to by something else
  335. # (for instance, as part of the instructions in a dockerfile).
  336. with open(dst, "a") as outfile:
  337. # In case the existing file doesn't end with a newline
  338. outfile.write("\n")
  339. outfile.write(rendered)
  340. def add_worker_roles_to_shared_config(
  341. shared_config: dict,
  342. worker_types_set: Set[str],
  343. worker_name: str,
  344. worker_port: int,
  345. ) -> None:
  346. """Given a dictionary representing a config file shared across all workers,
  347. append appropriate worker information to it for the current worker_type instance.
  348. Args:
  349. shared_config: The config dict that all worker instances share (after being
  350. converted to YAML)
  351. worker_types_set: The type of worker (one of those defined in WORKERS_CONFIG).
  352. This list can be a single worker type or multiple.
  353. worker_name: The name of the worker instance.
  354. worker_port: The HTTP replication port that the worker instance is listening on.
  355. """
  356. # The instance_map config field marks the workers that write to various replication
  357. # streams
  358. instance_map = shared_config.setdefault("instance_map", {})
  359. # This is a list of the stream_writers that there can be only one of. Events can be
  360. # sharded, and therefore doesn't belong here.
  361. singular_stream_writers = [
  362. "account_data",
  363. "presence",
  364. "receipts",
  365. "to_device",
  366. "typing",
  367. ]
  368. # Worker-type specific sharding config. Now a single worker can fulfill multiple
  369. # roles, check each.
  370. if "pusher" in worker_types_set:
  371. shared_config.setdefault("pusher_instances", []).append(worker_name)
  372. if "federation_sender" in worker_types_set:
  373. shared_config.setdefault("federation_sender_instances", []).append(worker_name)
  374. if "event_persister" in worker_types_set:
  375. # Event persisters write to the events stream, so we need to update
  376. # the list of event stream writers
  377. shared_config.setdefault("stream_writers", {}).setdefault("events", []).append(
  378. worker_name
  379. )
  380. # Map of stream writer instance names to host/ports combos
  381. instance_map[worker_name] = {
  382. "host": "localhost",
  383. "port": worker_port,
  384. }
  385. # Update the list of stream writers. It's convenient that the name of the worker
  386. # type is the same as the stream to write. Iterate over the whole list in case there
  387. # is more than one.
  388. for worker in worker_types_set:
  389. if worker in singular_stream_writers:
  390. shared_config.setdefault("stream_writers", {}).setdefault(
  391. worker, []
  392. ).append(worker_name)
  393. # Map of stream writer instance names to host/ports combos
  394. # For now, all stream writers need http replication ports
  395. instance_map[worker_name] = {
  396. "host": "localhost",
  397. "port": worker_port,
  398. }
  399. def merge_worker_template_configs(
  400. existing_dict: Optional[Dict[str, Any]],
  401. to_be_merged_dict: Dict[str, Any],
  402. ) -> Dict[str, Any]:
  403. """When given an existing dict of worker template configuration consisting with both
  404. dicts and lists, merge new template data from WORKERS_CONFIG(or create) and
  405. return new dict.
  406. Args:
  407. existing_dict: Either an existing worker template or a fresh blank one.
  408. to_be_merged_dict: The template from WORKERS_CONFIGS to be merged into
  409. existing_dict.
  410. Returns: The newly merged together dict values.
  411. """
  412. new_dict: Dict[str, Any] = {}
  413. if not existing_dict:
  414. # It doesn't exist yet, just use the new dict(but take a copy not a reference)
  415. new_dict = to_be_merged_dict.copy()
  416. else:
  417. for i in to_be_merged_dict.keys():
  418. if (i == "endpoint_patterns") or (i == "listener_resources"):
  419. # merge the two lists, remove duplicates
  420. new_dict[i] = list(set(existing_dict[i] + to_be_merged_dict[i]))
  421. elif i == "shared_extra_conf":
  422. # merge dictionary's, the worker name will be replaced later
  423. new_dict[i] = {**existing_dict[i], **to_be_merged_dict[i]}
  424. elif i == "worker_extra_conf":
  425. # There is only one worker type that has a 'worker_extra_conf' and it is
  426. # the media_repo. Since duplicate worker types on the same worker don't
  427. # work, this is fine.
  428. new_dict[i] = existing_dict[i] + to_be_merged_dict[i]
  429. else:
  430. # Everything else should be identical, like "app", which only works
  431. # because all apps are now generic_workers.
  432. new_dict[i] = to_be_merged_dict[i]
  433. return new_dict
  434. def insert_worker_name_for_worker_config(
  435. existing_dict: Dict[str, Any], worker_name: str
  436. ) -> Dict[str, Any]:
  437. """Insert a given worker name into the worker's configuration dict.
  438. Args:
  439. existing_dict: The worker_config dict that is imported into shared_config.
  440. worker_name: The name of the worker to insert.
  441. Returns: Copy of the dict with newly inserted worker name
  442. """
  443. dict_to_edit = existing_dict.copy()
  444. for k, v in dict_to_edit["shared_extra_conf"].items():
  445. # Only proceed if it's the placeholder name string
  446. if v == WORKER_PLACEHOLDER_NAME:
  447. dict_to_edit["shared_extra_conf"][k] = worker_name
  448. return dict_to_edit
  449. def apply_requested_multiplier_for_worker(worker_types: List[str]) -> List[str]:
  450. """
  451. Apply multiplier(if found) by returning a new expanded list with some basic error
  452. checking.
  453. Args:
  454. worker_types: The unprocessed List of requested workers
  455. Returns:
  456. A new list with all requested workers expanded.
  457. """
  458. # Checking performed:
  459. # 1. if worker:2 or more is declared, it will create additional workers up to number
  460. # 2. if worker:1, it will create a single copy of this worker as if no number was
  461. # given
  462. # 3. if worker:0 is declared, this worker will be ignored. This is to allow for
  463. # scripting and automated expansion and is intended behaviour.
  464. # 4. if worker:NaN or is a negative number, it will error and log it.
  465. new_worker_types = []
  466. for worker_type in worker_types:
  467. if ":" in worker_type:
  468. worker_type_components = split_and_strip_string(worker_type, ":", 1)
  469. worker_count = 0
  470. # Should only be 2 components, a type of worker(s) and an integer as a
  471. # string. Cast the number as an int then it can be used as a counter.
  472. try:
  473. worker_count = int(worker_type_components[1])
  474. except ValueError:
  475. error(
  476. f"Bad number in worker count for '{worker_type}': "
  477. f"'{worker_type_components[1]}' is not an integer"
  478. )
  479. # As long as there are more than 0, we add one to the list to make below.
  480. for _ in range(worker_count):
  481. new_worker_types.append(worker_type_components[0])
  482. else:
  483. # If it's not a real worker_type, it will error out later.
  484. new_worker_types.append(worker_type)
  485. return new_worker_types
  486. def is_sharding_allowed_for_worker_type(worker_type: str) -> bool:
  487. """Helper to check to make sure worker types that cannot have multiples do not.
  488. Args:
  489. worker_type: The type of worker to check against.
  490. Returns: True if allowed, False if not
  491. """
  492. return worker_type not in [
  493. "background_worker",
  494. "account_data",
  495. "presence",
  496. "receipts",
  497. "typing",
  498. "to_device",
  499. ]
  500. def split_and_strip_string(
  501. given_string: str, split_char: str, max_split: SupportsIndex = -1
  502. ) -> List[str]:
  503. """
  504. Helper to split a string on split_char and strip whitespace from each end of each
  505. element.
  506. Args:
  507. given_string: The string to split
  508. split_char: The character to split the string on
  509. max_split: kwarg for split() to limit how many times the split() happens
  510. Returns:
  511. A List of strings
  512. """
  513. # Removes whitespace from ends of result strings before adding to list. Allow for
  514. # overriding 'maxsplit' kwarg, default being -1 to signify no maximum.
  515. return [x.strip() for x in given_string.split(split_char, maxsplit=max_split)]
  516. def generate_base_homeserver_config() -> None:
  517. """Starts Synapse and generates a basic homeserver config, which will later be
  518. modified for worker support.
  519. Raises: CalledProcessError if calling start.py returned a non-zero exit code.
  520. """
  521. # start.py already does this for us, so just call that.
  522. # note that this script is copied in in the official, monolith dockerfile
  523. os.environ["SYNAPSE_HTTP_PORT"] = str(MAIN_PROCESS_HTTP_LISTENER_PORT)
  524. subprocess.run(["/usr/local/bin/python", "/start.py", "migrate_config"], check=True)
  525. def parse_worker_types(
  526. requested_worker_types: List[str],
  527. ) -> Dict[str, Set[str]]:
  528. """Read the desired list of requested workers and prepare the data for use in
  529. generating worker config files while also checking for potential gotchas.
  530. Args:
  531. requested_worker_types: The list formed from the split environment variable
  532. containing the unprocessed requests for workers.
  533. Returns: A dict of worker names to set of worker types. Format:
  534. {'worker_name':
  535. {'worker_type', 'worker_type2'}
  536. }
  537. """
  538. # A counter of worker_base_name -> int. Used for determining the name for a given
  539. # worker when generating its config file, as each worker's name is just
  540. # worker_base_name followed by instance number
  541. worker_base_name_counter: Dict[str, int] = defaultdict(int)
  542. # Similar to above, but more finely grained. This is used to determine we don't have
  543. # more than a single worker for cases where multiples would be bad(e.g. presence).
  544. worker_type_shard_counter: Dict[str, int] = defaultdict(int)
  545. # The final result of all this processing
  546. dict_to_return: Dict[str, Set[str]] = {}
  547. # Handle any multipliers requested for given workers.
  548. multiple_processed_worker_types = apply_requested_multiplier_for_worker(
  549. requested_worker_types
  550. )
  551. # Process each worker_type_string
  552. # Examples of expected formats:
  553. # - requested_name=type1+type2+type3
  554. # - synchrotron
  555. # - event_creator+event_persister
  556. for worker_type_string in multiple_processed_worker_types:
  557. # First, if a name is requested, use that — otherwise generate one.
  558. worker_base_name: str = ""
  559. if "=" in worker_type_string:
  560. # Split on "=", remove extra whitespace from ends then make list
  561. worker_type_split = split_and_strip_string(worker_type_string, "=")
  562. if len(worker_type_split) > 2:
  563. error(
  564. "There should only be one '=' in the worker type string. "
  565. f"Please fix: {worker_type_string}"
  566. )
  567. # Assign the name
  568. worker_base_name = worker_type_split[0]
  569. if not re.match(r"^[a-zA-Z0-9_+-]*[a-zA-Z_+-]$", worker_base_name):
  570. # Apply a fairly narrow regex to the worker names. Some characters
  571. # aren't safe for use in file paths or nginx configurations.
  572. # Don't allow to end with a number because we'll add a number
  573. # ourselves in a moment.
  574. error(
  575. "Invalid worker name; please choose a name consisting of "
  576. "alphanumeric letters, _ + -, but not ending with a digit: "
  577. f"{worker_base_name!r}"
  578. )
  579. # Continue processing the remainder of the worker_type string
  580. # with the name override removed.
  581. worker_type_string = worker_type_split[1]
  582. # Split the worker_type_string on "+", remove whitespace from ends then make
  583. # the list a set so it's deduplicated.
  584. worker_types_set: Set[str] = set(
  585. split_and_strip_string(worker_type_string, "+")
  586. )
  587. if not worker_base_name:
  588. # No base name specified: generate one deterministically from set of
  589. # types
  590. worker_base_name = "+".join(sorted(worker_types_set))
  591. # At this point, we have:
  592. # worker_base_name which is the name for the worker, without counter.
  593. # worker_types_set which is the set of worker types for this worker.
  594. # Validate worker_type and make sure we don't allow sharding for a worker type
  595. # that doesn't support it. Will error and stop if it is a problem,
  596. # e.g. 'background_worker'.
  597. for worker_type in worker_types_set:
  598. # Verify this is a real defined worker type. If it's not, stop everything so
  599. # it can be fixed.
  600. if worker_type not in WORKERS_CONFIG:
  601. error(
  602. f"{worker_type} is an unknown worker type! Was found in "
  603. f"'{worker_type_string}'. Please fix!"
  604. )
  605. if worker_type in worker_type_shard_counter:
  606. if not is_sharding_allowed_for_worker_type(worker_type):
  607. error(
  608. f"There can be only a single worker with {worker_type} "
  609. "type. Please recount and remove."
  610. )
  611. # Not in shard counter, must not have seen it yet, add it.
  612. worker_type_shard_counter[worker_type] += 1
  613. # Generate the number for the worker using incrementing counter
  614. worker_base_name_counter[worker_base_name] += 1
  615. worker_number = worker_base_name_counter[worker_base_name]
  616. worker_name = f"{worker_base_name}{worker_number}"
  617. if worker_number > 1:
  618. # If this isn't the first worker, check that we don't have a confusing
  619. # mixture of worker types with the same base name.
  620. first_worker_with_base_name = dict_to_return[f"{worker_base_name}1"]
  621. if first_worker_with_base_name != worker_types_set:
  622. error(
  623. f"Can not use worker_name: '{worker_name}' for worker_type(s): "
  624. f"{worker_types_set!r}. It is already in use by "
  625. f"worker_type(s): {first_worker_with_base_name!r}"
  626. )
  627. dict_to_return[worker_name] = worker_types_set
  628. return dict_to_return
  629. def generate_worker_files(
  630. environ: Mapping[str, str],
  631. config_path: str,
  632. data_dir: str,
  633. requested_worker_types: Dict[str, Set[str]],
  634. ) -> None:
  635. """Read the desired workers(if any) that is passed in and generate shared
  636. homeserver, nginx and supervisord configs.
  637. Args:
  638. environ: os.environ instance.
  639. config_path: The location of the generated Synapse main worker config file.
  640. data_dir: The location of the synapse data directory. Where log and
  641. user-facing config files live.
  642. requested_worker_types: A Dict containing requested workers in the format of
  643. {'worker_name1': {'worker_type', ...}}
  644. """
  645. # Note that yaml cares about indentation, so care should be taken to insert lines
  646. # into files at the correct indentation below.
  647. # First read the original config file and extract the listeners block. Then we'll
  648. # add another listener for replication. Later we'll write out the result to the
  649. # shared config file.
  650. listeners = [
  651. {
  652. "port": MAIN_PROCESS_REPLICATION_PORT,
  653. "bind_address": MAIN_PROCESS_LOCALHOST_ADDRESS,
  654. "type": "http",
  655. "resources": [{"names": ["replication"]}],
  656. }
  657. ]
  658. with open(config_path) as file_stream:
  659. original_config = yaml.safe_load(file_stream)
  660. original_listeners = original_config.get("listeners")
  661. if original_listeners:
  662. listeners += original_listeners
  663. # The shared homeserver config. The contents of which will be inserted into the
  664. # base shared worker jinja2 template. This config file will be passed to all
  665. # workers, included Synapse's main process. It is intended mainly for disabling
  666. # functionality when certain workers are spun up, and adding a replication listener.
  667. shared_config: Dict[str, Any] = {"listeners": listeners}
  668. # List of dicts that describe workers.
  669. # We pass this to the Supervisor template later to generate the appropriate
  670. # program blocks.
  671. worker_descriptors: List[Dict[str, Any]] = []
  672. # Upstreams for load-balancing purposes. This dict takes the form of the worker
  673. # type to the ports of each worker. For example:
  674. # {
  675. # worker_type: {1234, 1235, ...}}
  676. # }
  677. # and will be used to construct 'upstream' nginx directives.
  678. nginx_upstreams: Dict[str, Set[int]] = {}
  679. # A map of: {"endpoint": "upstream"}, where "upstream" is a str representing what
  680. # will be placed after the proxy_pass directive. The main benefit to representing
  681. # this data as a dict over a str is that we can easily deduplicate endpoints
  682. # across multiple instances of the same worker. The final rendering will be combined
  683. # with nginx_upstreams and placed in /etc/nginx/conf.d.
  684. nginx_locations: Dict[str, str] = {}
  685. # Create the worker configuration directory if it doesn't already exist
  686. os.makedirs("/conf/workers", exist_ok=True)
  687. # Start worker ports from this arbitrary port
  688. worker_port = 18009
  689. # A list of internal endpoints to healthcheck, starting with the main process
  690. # which exists even if no workers do.
  691. healthcheck_urls = ["http://localhost:8080/health"]
  692. # Get the set of all worker types that we have configured
  693. all_worker_types_in_use = set(chain(*requested_worker_types.values()))
  694. # Map locations to upstreams (corresponding to worker types) in Nginx
  695. # but only if we use the appropriate worker type
  696. for worker_type in all_worker_types_in_use:
  697. for endpoint_pattern in WORKERS_CONFIG[worker_type]["endpoint_patterns"]:
  698. nginx_locations[endpoint_pattern] = f"http://{worker_type}"
  699. # For each worker type specified by the user, create config values and write it's
  700. # yaml config file
  701. for worker_name, worker_types_set in requested_worker_types.items():
  702. # The collected and processed data will live here.
  703. worker_config: Dict[str, Any] = {}
  704. # Merge all worker config templates for this worker into a single config
  705. for worker_type in worker_types_set:
  706. copy_of_template_config = WORKERS_CONFIG[worker_type].copy()
  707. # Merge worker type template configuration data. It's a combination of lists
  708. # and dicts, so use this helper.
  709. worker_config = merge_worker_template_configs(
  710. worker_config, copy_of_template_config
  711. )
  712. # Replace placeholder names in the config template with the actual worker name.
  713. worker_config = insert_worker_name_for_worker_config(worker_config, worker_name)
  714. worker_config.update(
  715. {"name": worker_name, "port": str(worker_port), "config_path": config_path}
  716. )
  717. # Update the shared config with any worker_type specific options. The first of a
  718. # given worker_type needs to stay assigned and not be replaced.
  719. worker_config["shared_extra_conf"].update(shared_config)
  720. shared_config = worker_config["shared_extra_conf"]
  721. healthcheck_urls.append("http://localhost:%d/health" % (worker_port,))
  722. # Update the shared config with sharding-related options if necessary
  723. add_worker_roles_to_shared_config(
  724. shared_config, worker_types_set, worker_name, worker_port
  725. )
  726. # Enable the worker in supervisord
  727. worker_descriptors.append(worker_config)
  728. # Write out the worker's logging config file
  729. log_config_filepath = generate_worker_log_config(environ, worker_name, data_dir)
  730. # Then a worker config file
  731. convert(
  732. "/conf/worker.yaml.j2",
  733. "/conf/workers/{name}.yaml".format(name=worker_name),
  734. **worker_config,
  735. worker_log_config_filepath=log_config_filepath,
  736. )
  737. # Save this worker's port number to the correct nginx upstreams
  738. for worker_type in worker_types_set:
  739. nginx_upstreams.setdefault(worker_type, set()).add(worker_port)
  740. worker_port += 1
  741. # Build the nginx location config blocks
  742. nginx_location_config = ""
  743. for endpoint, upstream in nginx_locations.items():
  744. nginx_location_config += NGINX_LOCATION_CONFIG_BLOCK.format(
  745. endpoint=endpoint,
  746. upstream=upstream,
  747. )
  748. # Determine the load-balancing upstreams to configure
  749. nginx_upstream_config = ""
  750. for upstream_worker_base_name, upstream_worker_ports in nginx_upstreams.items():
  751. body = ""
  752. for port in upstream_worker_ports:
  753. body += f" server localhost:{port};\n"
  754. # Add to the list of configured upstreams
  755. nginx_upstream_config += NGINX_UPSTREAM_CONFIG_BLOCK.format(
  756. upstream_worker_base_name=upstream_worker_base_name,
  757. body=body,
  758. )
  759. # Finally, we'll write out the config files.
  760. # log config for the master process
  761. master_log_config = generate_worker_log_config(environ, "master", data_dir)
  762. shared_config["log_config"] = master_log_config
  763. # Find application service registrations
  764. appservice_registrations = None
  765. appservice_registration_dir = os.environ.get("SYNAPSE_AS_REGISTRATION_DIR")
  766. if appservice_registration_dir:
  767. # Scan for all YAML files that should be application service registrations.
  768. appservice_registrations = [
  769. str(reg_path.resolve())
  770. for reg_path in Path(appservice_registration_dir).iterdir()
  771. if reg_path.suffix.lower() in (".yaml", ".yml")
  772. ]
  773. workers_in_use = len(requested_worker_types) > 0
  774. # If there are workers, add the main process to the instance_map too.
  775. if workers_in_use:
  776. instance_map = shared_config.setdefault("instance_map", {})
  777. instance_map[MAIN_PROCESS_INSTANCE_NAME] = {
  778. "host": MAIN_PROCESS_LOCALHOST_ADDRESS,
  779. "port": MAIN_PROCESS_REPLICATION_PORT,
  780. }
  781. # Shared homeserver config
  782. convert(
  783. "/conf/shared.yaml.j2",
  784. "/conf/workers/shared.yaml",
  785. shared_worker_config=yaml.dump(shared_config),
  786. appservice_registrations=appservice_registrations,
  787. enable_redis=workers_in_use,
  788. workers_in_use=workers_in_use,
  789. )
  790. # Nginx config
  791. convert(
  792. "/conf/nginx.conf.j2",
  793. "/etc/nginx/conf.d/matrix-synapse.conf",
  794. worker_locations=nginx_location_config,
  795. upstream_directives=nginx_upstream_config,
  796. tls_cert_path=os.environ.get("SYNAPSE_TLS_CERT"),
  797. tls_key_path=os.environ.get("SYNAPSE_TLS_KEY"),
  798. )
  799. # Supervisord config
  800. os.makedirs("/etc/supervisor", exist_ok=True)
  801. convert(
  802. "/conf/supervisord.conf.j2",
  803. "/etc/supervisor/supervisord.conf",
  804. main_config_path=config_path,
  805. enable_redis=workers_in_use,
  806. )
  807. convert(
  808. "/conf/synapse.supervisord.conf.j2",
  809. "/etc/supervisor/conf.d/synapse.conf",
  810. workers=worker_descriptors,
  811. main_config_path=config_path,
  812. use_forking_launcher=environ.get("SYNAPSE_USE_EXPERIMENTAL_FORKING_LAUNCHER"),
  813. )
  814. # healthcheck config
  815. convert(
  816. "/conf/healthcheck.sh.j2",
  817. "/healthcheck.sh",
  818. healthcheck_urls=healthcheck_urls,
  819. )
  820. # Ensure the logging directory exists
  821. log_dir = data_dir + "/logs"
  822. if not os.path.exists(log_dir):
  823. os.mkdir(log_dir)
  824. def generate_worker_log_config(
  825. environ: Mapping[str, str], worker_name: str, data_dir: str
  826. ) -> str:
  827. """Generate a log.config file for the given worker.
  828. Returns: the path to the generated file
  829. """
  830. # Check whether we should write worker logs to disk, in addition to the console
  831. extra_log_template_args: Dict[str, Optional[str]] = {}
  832. if environ.get("SYNAPSE_WORKERS_WRITE_LOGS_TO_DISK"):
  833. extra_log_template_args["LOG_FILE_PATH"] = f"{data_dir}/logs/{worker_name}.log"
  834. extra_log_template_args["SYNAPSE_LOG_LEVEL"] = environ.get("SYNAPSE_LOG_LEVEL")
  835. extra_log_template_args["SYNAPSE_LOG_SENSITIVE"] = environ.get(
  836. "SYNAPSE_LOG_SENSITIVE"
  837. )
  838. # Render and write the file
  839. log_config_filepath = f"/conf/workers/{worker_name}.log.config"
  840. convert(
  841. "/conf/log.config",
  842. log_config_filepath,
  843. worker_name=worker_name,
  844. **extra_log_template_args,
  845. include_worker_name_in_log_line=environ.get(
  846. "SYNAPSE_USE_EXPERIMENTAL_FORKING_LAUNCHER"
  847. ),
  848. )
  849. return log_config_filepath
  850. def main(args: List[str], environ: MutableMapping[str, str]) -> None:
  851. config_dir = environ.get("SYNAPSE_CONFIG_DIR", "/data")
  852. config_path = environ.get("SYNAPSE_CONFIG_PATH", config_dir + "/homeserver.yaml")
  853. data_dir = environ.get("SYNAPSE_DATA_DIR", "/data")
  854. # override SYNAPSE_NO_TLS, we don't support TLS in worker mode,
  855. # this needs to be handled by a frontend proxy
  856. environ["SYNAPSE_NO_TLS"] = "yes"
  857. # Generate the base homeserver config if one does not yet exist
  858. if not os.path.exists(config_path):
  859. log("Generating base homeserver config")
  860. generate_base_homeserver_config()
  861. else:
  862. log("Base homeserver config exists—not regenerating")
  863. # This script may be run multiple times (mostly by Complement, see note at top of
  864. # file). Don't re-configure workers in this instance.
  865. mark_filepath = "/conf/workers_have_been_configured"
  866. if not os.path.exists(mark_filepath):
  867. # Collect and validate worker_type requests
  868. # Read the desired worker configuration from the environment
  869. worker_types_env = environ.get("SYNAPSE_WORKER_TYPES", "").strip()
  870. # Only process worker_types if they exist
  871. if not worker_types_env:
  872. # No workers, just the main process
  873. worker_types = []
  874. requested_worker_types: Dict[str, Any] = {}
  875. else:
  876. # Split type names by comma, ignoring whitespace.
  877. worker_types = split_and_strip_string(worker_types_env, ",")
  878. requested_worker_types = parse_worker_types(worker_types)
  879. # Always regenerate all other config files
  880. log("Generating worker config files")
  881. generate_worker_files(environ, config_path, data_dir, requested_worker_types)
  882. # Mark workers as being configured
  883. with open(mark_filepath, "w") as f:
  884. f.write("")
  885. else:
  886. log("Worker config exists—not regenerating")
  887. # Lifted right out of start.py
  888. jemallocpath = "/usr/lib/%s-linux-gnu/libjemalloc.so.2" % (platform.machine(),)
  889. if os.path.isfile(jemallocpath):
  890. environ["LD_PRELOAD"] = jemallocpath
  891. else:
  892. log("Could not find %s, will not use" % (jemallocpath,))
  893. # Start supervisord, which will start Synapse, all of the configured worker
  894. # processes, redis, nginx etc. according to the config we created above.
  895. log("Starting supervisord")
  896. flush_buffers()
  897. os.execle(
  898. "/usr/local/bin/supervisord",
  899. "supervisord",
  900. "-c",
  901. "/etc/supervisor/supervisord.conf",
  902. environ,
  903. )
  904. if __name__ == "__main__":
  905. main(sys.argv, os.environ)