1
0

start.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/local/bin/python
  2. import jinja2
  3. import os
  4. import sys
  5. import subprocess
  6. import glob
  7. import codecs
  8. # Utility functions
  9. convert = lambda src, dst, environ: open(dst, "w").write(jinja2.Template(open(src).read()).render(**environ))
  10. def check_arguments(environ, args):
  11. for argument in args:
  12. if argument not in environ:
  13. print("Environment variable %s is mandatory, exiting." % argument)
  14. sys.exit(2)
  15. def generate_secrets(environ, secrets):
  16. for name, secret in secrets.items():
  17. if secret not in environ:
  18. filename = "/data/%s.%s.key" % (environ["SYNAPSE_SERVER_NAME"], name)
  19. if os.path.exists(filename):
  20. with open(filename) as handle: value = handle.read()
  21. else:
  22. print("Generating a random secret for {}".format(name))
  23. value = codecs.encode(os.urandom(32), "hex").decode()
  24. with open(filename, "w") as handle: handle.write(value)
  25. environ[secret] = value
  26. # Prepare the configuration
  27. mode = sys.argv[1] if len(sys.argv) > 1 else None
  28. environ = os.environ.copy()
  29. ownership = "{}:{}".format(environ.get("UID", 991), environ.get("GID", 991))
  30. args = ["python", "-m", "synapse.app.homeserver"]
  31. # In generate mode, generate a configuration, missing keys, then exit
  32. if mode == "generate":
  33. check_arguments(environ, ("SYNAPSE_SERVER_NAME", "SYNAPSE_REPORT_STATS", "SYNAPSE_CONFIG_PATH"))
  34. args += [
  35. "--server-name", environ["SYNAPSE_SERVER_NAME"],
  36. "--report-stats", environ["SYNAPSE_REPORT_STATS"],
  37. "--config-path", environ["SYNAPSE_CONFIG_PATH"],
  38. "--generate-config"
  39. ]
  40. os.execv("/usr/local/bin/python", args)
  41. # In normal mode, generate missing keys if any, then run synapse
  42. else:
  43. # Parse the configuration file
  44. if "SYNAPSE_CONFIG_PATH" in environ:
  45. args += ["--config-path", environ["SYNAPSE_CONFIG_PATH"]]
  46. else:
  47. check_arguments(environ, ("SYNAPSE_SERVER_NAME", "SYNAPSE_REPORT_STATS"))
  48. generate_secrets(environ, {
  49. "registration": "SYNAPSE_REGISTRATION_SHARED_SECRET",
  50. "macaroon": "SYNAPSE_MACAROON_SECRET_KEY"
  51. })
  52. environ["SYNAPSE_APPSERVICES"] = glob.glob("/data/appservices/*.yaml")
  53. if not os.path.exists("/compiled"): os.mkdir("/compiled")
  54. convert("/conf/homeserver.yaml", "/compiled/homeserver.yaml", environ)
  55. convert("/conf/log.config", "/compiled/log.config", environ)
  56. subprocess.check_output(["chown", "-R", ownership, "/data"])
  57. args += ["--config-path", "/compiled/homeserver.yaml"]
  58. # Generate missing keys and start synapse
  59. subprocess.check_output(args + ["--generate-keys"])
  60. os.execv("/sbin/su-exec", ["su-exec", ownership] + args)