start.py 2.7 KB

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