start.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. #!/usr/local/bin/python
  2. import codecs
  3. import glob
  4. import os
  5. import platform
  6. import subprocess
  7. import sys
  8. import jinja2
  9. # Utility functions
  10. def log(txt):
  11. print(txt, file=sys.stderr)
  12. def error(txt):
  13. log(txt)
  14. sys.exit(2)
  15. def convert(src, dst, environ):
  16. """Generate a file from a template
  17. Args:
  18. src (str): path to input file
  19. dst (str): path to file to write
  20. environ (dict): environment dictionary, for replacement mappings.
  21. """
  22. with open(src) as infile:
  23. template = infile.read()
  24. rendered = jinja2.Template(template).render(**environ)
  25. with open(dst, "w") as outfile:
  26. outfile.write(rendered)
  27. def generate_config_from_template(config_dir, config_path, environ, ownership):
  28. """Generate a homeserver.yaml from environment variables
  29. Args:
  30. config_dir (str): where to put generated config files
  31. config_path (str): where to put the main config file
  32. environ (dict): environment dictionary
  33. ownership (str|None): "<user>:<group>" string which will be used to set
  34. ownership of the generated configs. If None, ownership will not change.
  35. """
  36. for v in ("SYNAPSE_SERVER_NAME", "SYNAPSE_REPORT_STATS"):
  37. if v not in environ:
  38. error(
  39. "Environment variable '%s' is mandatory when generating a config file."
  40. % (v,)
  41. )
  42. # populate some params from data files (if they exist, else create new ones)
  43. environ = environ.copy()
  44. secrets = {
  45. "registration": "SYNAPSE_REGISTRATION_SHARED_SECRET",
  46. "macaroon": "SYNAPSE_MACAROON_SECRET_KEY",
  47. }
  48. for name, secret in secrets.items():
  49. if secret not in environ:
  50. filename = "/data/%s.%s.key" % (environ["SYNAPSE_SERVER_NAME"], name)
  51. # if the file already exists, load in the existing value; otherwise,
  52. # generate a new secret and write it to a file
  53. if os.path.exists(filename):
  54. log("Reading %s from %s" % (secret, filename))
  55. with open(filename) as handle:
  56. value = handle.read()
  57. else:
  58. log("Generating a random secret for {}".format(secret))
  59. value = codecs.encode(os.urandom(32), "hex").decode()
  60. with open(filename, "w") as handle:
  61. handle.write(value)
  62. environ[secret] = value
  63. environ["SYNAPSE_APPSERVICES"] = glob.glob("/data/appservices/*.yaml")
  64. if not os.path.exists(config_dir):
  65. os.mkdir(config_dir)
  66. # Convert SYNAPSE_NO_TLS to boolean if exists
  67. if "SYNAPSE_NO_TLS" in environ:
  68. tlsanswerstring = str.lower(environ["SYNAPSE_NO_TLS"])
  69. if tlsanswerstring in ("true", "on", "1", "yes"):
  70. environ["SYNAPSE_NO_TLS"] = True
  71. else:
  72. if tlsanswerstring in ("false", "off", "0", "no"):
  73. environ["SYNAPSE_NO_TLS"] = False
  74. else:
  75. error(
  76. 'Environment variable "SYNAPSE_NO_TLS" found but value "'
  77. + tlsanswerstring
  78. + '" unrecognized; exiting.'
  79. )
  80. if "SYNAPSE_LOG_CONFIG" not in environ:
  81. environ["SYNAPSE_LOG_CONFIG"] = config_dir + "/log.config"
  82. log("Generating synapse config file " + config_path)
  83. convert("/conf/homeserver.yaml", config_path, environ)
  84. log_config_file = environ["SYNAPSE_LOG_CONFIG"]
  85. log("Generating log config file " + log_config_file)
  86. convert("/conf/log.config", log_config_file, environ)
  87. # Hopefully we already have a signing key, but generate one if not.
  88. args = [
  89. "python",
  90. "-m",
  91. "synapse.app.homeserver",
  92. "--config-path",
  93. config_path,
  94. # tell synapse to put generated keys in /data rather than /compiled
  95. "--keys-directory",
  96. config_dir,
  97. "--generate-keys",
  98. ]
  99. if ownership is not None:
  100. log(f"Setting ownership on /data to {ownership}")
  101. subprocess.check_output(["chown", "-R", ownership, "/data"])
  102. args = ["gosu", ownership] + args
  103. subprocess.check_output(args)
  104. def run_generate_config(environ, ownership):
  105. """Run synapse with a --generate-config param to generate a template config file
  106. Args:
  107. environ (dict): env var dict
  108. ownership (str|None): "userid:groupid" arg for chmod. If None, ownership will not change.
  109. Never returns.
  110. """
  111. for v in ("SYNAPSE_SERVER_NAME", "SYNAPSE_REPORT_STATS"):
  112. if v not in environ:
  113. error("Environment variable '%s' is mandatory in `generate` mode." % (v,))
  114. server_name = environ["SYNAPSE_SERVER_NAME"]
  115. config_dir = environ.get("SYNAPSE_CONFIG_DIR", "/data")
  116. config_path = environ.get("SYNAPSE_CONFIG_PATH", config_dir + "/homeserver.yaml")
  117. data_dir = environ.get("SYNAPSE_DATA_DIR", "/data")
  118. if ownership is not None:
  119. # make sure that synapse has perms to write to the data dir.
  120. log(f"Setting ownership on {data_dir} to {ownership}")
  121. subprocess.check_output(["chown", ownership, data_dir])
  122. # create a suitable log config from our template
  123. log_config_file = "%s/%s.log.config" % (config_dir, server_name)
  124. if not os.path.exists(log_config_file):
  125. log("Creating log config %s" % (log_config_file,))
  126. convert("/conf/log.config", log_config_file, environ)
  127. # generate the main config file, and a signing key.
  128. args = [
  129. "python",
  130. "-m",
  131. "synapse.app.homeserver",
  132. "--server-name",
  133. server_name,
  134. "--report-stats",
  135. environ["SYNAPSE_REPORT_STATS"],
  136. "--config-path",
  137. config_path,
  138. "--config-directory",
  139. config_dir,
  140. "--data-directory",
  141. data_dir,
  142. "--generate-config",
  143. "--open-private-ports",
  144. ]
  145. # log("running %s" % (args, ))
  146. os.execv("/usr/local/bin/python", args)
  147. def main(args, environ):
  148. mode = args[1] if len(args) > 1 else "run"
  149. # if we were given an explicit user to switch to, do so
  150. ownership = None
  151. if "UID" in environ:
  152. desired_uid = int(environ["UID"])
  153. desired_gid = int(environ.get("GID", "991"))
  154. ownership = f"{desired_uid}:{desired_gid}"
  155. elif os.getuid() == 0:
  156. # otherwise, if we are running as root, use user 991
  157. ownership = "991:991"
  158. synapse_worker = environ.get("SYNAPSE_WORKER", "synapse.app.homeserver")
  159. # In generate mode, generate a configuration and missing keys, then exit
  160. if mode == "generate":
  161. return run_generate_config(environ, ownership)
  162. if mode == "migrate_config":
  163. # generate a config based on environment vars.
  164. config_dir = environ.get("SYNAPSE_CONFIG_DIR", "/data")
  165. config_path = environ.get(
  166. "SYNAPSE_CONFIG_PATH", config_dir + "/homeserver.yaml"
  167. )
  168. return generate_config_from_template(
  169. config_dir, config_path, environ, ownership
  170. )
  171. if mode != "run":
  172. error("Unknown execution mode '%s'" % (mode,))
  173. args = args[2:]
  174. if "-m" not in args:
  175. args = ["-m", synapse_worker] + args
  176. jemallocpath = "/usr/lib/%s-linux-gnu/libjemalloc.so.2" % (platform.machine(),)
  177. if os.path.isfile(jemallocpath):
  178. environ["LD_PRELOAD"] = jemallocpath
  179. else:
  180. log("Could not find %s, will not use" % (jemallocpath,))
  181. # if there are no config files passed to synapse, try adding the default file
  182. if not any(p.startswith("--config-path") or p.startswith("-c") for p in args):
  183. config_dir = environ.get("SYNAPSE_CONFIG_DIR", "/data")
  184. config_path = environ.get(
  185. "SYNAPSE_CONFIG_PATH", config_dir + "/homeserver.yaml"
  186. )
  187. if not os.path.exists(config_path):
  188. if "SYNAPSE_SERVER_NAME" in environ:
  189. error(
  190. """\
  191. Config file '%s' does not exist.
  192. The synapse docker image no longer supports generating a config file on-the-fly
  193. based on environment variables. You can migrate to a static config file by
  194. running with 'migrate_config'. See the README for more details.
  195. """
  196. % (config_path,)
  197. )
  198. error(
  199. "Config file '%s' does not exist. You should either create a new "
  200. "config file by running with the `generate` argument (and then edit "
  201. "the resulting file before restarting) or specify the path to an "
  202. "existing config file with the SYNAPSE_CONFIG_PATH variable."
  203. % (config_path,)
  204. )
  205. args += ["--config-path", config_path]
  206. log("Starting synapse with args " + " ".join(args))
  207. args = ["python"] + args
  208. if ownership is not None:
  209. args = ["gosu", ownership] + args
  210. os.execve("/usr/sbin/gosu", args, environ)
  211. else:
  212. os.execve("/usr/local/bin/python", args, environ)
  213. if __name__ == "__main__":
  214. main(sys.argv, os.environ)