synctl 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2014-2016 OpenMarket Ltd
  4. # Copyright 2018 New Vector Ltd
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import argparse
  18. import collections
  19. import errno
  20. import glob
  21. import os
  22. import os.path
  23. import signal
  24. import subprocess
  25. import sys
  26. import time
  27. from six import iteritems
  28. import yaml
  29. from synapse.config import find_config_files
  30. SYNAPSE = [sys.executable, "-B", "-m", "synapse.app.homeserver"]
  31. GREEN = "\x1b[1;32m"
  32. YELLOW = "\x1b[1;33m"
  33. RED = "\x1b[1;31m"
  34. NORMAL = "\x1b[m"
  35. def pid_running(pid):
  36. try:
  37. os.kill(pid, 0)
  38. return True
  39. except OSError as err:
  40. if err.errno == errno.EPERM:
  41. return True
  42. return False
  43. def write(message, colour=NORMAL, stream=sys.stdout):
  44. # Lets check if we're writing to a TTY before colouring
  45. should_colour = False
  46. try:
  47. should_colour = stream.isatty()
  48. except AttributeError:
  49. # Just in case `isatty` isn't defined on everything. The python
  50. # docs are incredibly vague.
  51. pass
  52. if not should_colour:
  53. stream.write(message + "\n")
  54. else:
  55. stream.write(colour + message + NORMAL + "\n")
  56. def abort(message, colour=RED, stream=sys.stderr):
  57. write(message, colour, stream)
  58. sys.exit(1)
  59. def start(configfile, daemonize=True):
  60. write("Starting ...")
  61. args = SYNAPSE
  62. if daemonize:
  63. args.extend(["--daemonize", "-c", configfile])
  64. else:
  65. args.extend(["-c", configfile])
  66. try:
  67. subprocess.check_call(args)
  68. write("started synapse.app.homeserver(%r)" % (configfile,), colour=GREEN)
  69. except subprocess.CalledProcessError as e:
  70. write(
  71. "error starting (exit code: %d); see above for logs" % e.returncode,
  72. colour=RED,
  73. )
  74. def start_worker(app, configfile, worker_configfile):
  75. args = [sys.executable, "-B", "-m", app, "-c", configfile, "-c", worker_configfile]
  76. try:
  77. subprocess.check_call(args)
  78. write("started %s(%r)" % (app, worker_configfile), colour=GREEN)
  79. except subprocess.CalledProcessError as e:
  80. write(
  81. "error starting %s(%r) (exit code: %d); see above for logs"
  82. % (app, worker_configfile, e.returncode),
  83. colour=RED,
  84. )
  85. def stop(pidfile, app):
  86. if os.path.exists(pidfile):
  87. pid = int(open(pidfile).read())
  88. try:
  89. os.kill(pid, signal.SIGTERM)
  90. write("stopped %s" % (app,), colour=GREEN)
  91. except OSError as err:
  92. if err.errno == errno.ESRCH:
  93. write("%s not running" % (app,), colour=YELLOW)
  94. elif err.errno == errno.EPERM:
  95. abort("Cannot stop %s: Operation not permitted" % (app,))
  96. else:
  97. abort("Cannot stop %s: Unknown error" % (app,))
  98. Worker = collections.namedtuple(
  99. "Worker", ["app", "configfile", "pidfile", "cache_factor", "cache_factors"]
  100. )
  101. def main():
  102. parser = argparse.ArgumentParser()
  103. parser.add_argument(
  104. "action",
  105. choices=["start", "stop", "restart"],
  106. help="whether to start, stop or restart the synapse",
  107. )
  108. parser.add_argument(
  109. "configfile",
  110. nargs="?",
  111. default="homeserver.yaml",
  112. help="the homeserver config file. Defaults to homeserver.yaml. May also be"
  113. " a directory with *.yaml files",
  114. )
  115. parser.add_argument(
  116. "-w", "--worker", metavar="WORKERCONFIG", help="start or stop a single worker"
  117. )
  118. parser.add_argument(
  119. "-a",
  120. "--all-processes",
  121. metavar="WORKERCONFIGDIR",
  122. help="start or stop all the workers in the given directory"
  123. " and the main synapse process",
  124. )
  125. parser.add_argument(
  126. "--no-daemonize",
  127. action="store_false",
  128. dest="daemonize",
  129. help="Run synapse in the foreground for debugging. "
  130. "Will work only if the daemonize option is not set in the config.",
  131. )
  132. options = parser.parse_args()
  133. if options.worker and options.all_processes:
  134. write('Cannot use "--worker" with "--all-processes"', stream=sys.stderr)
  135. sys.exit(1)
  136. if not options.daemonize and options.all_processes:
  137. write('Cannot use "--no-daemonize" with "--all-processes"', stream=sys.stderr)
  138. sys.exit(1)
  139. configfile = options.configfile
  140. if not os.path.exists(configfile):
  141. write(
  142. "No config file found\n"
  143. "To generate a config file, run '%s -c %s --generate-config"
  144. " --server-name=<server name> --report-stats=<yes/no>'\n"
  145. % (" ".join(SYNAPSE), options.configfile),
  146. stream=sys.stderr,
  147. )
  148. sys.exit(1)
  149. config_files = find_config_files([configfile])
  150. config = {}
  151. for config_file in config_files:
  152. with open(config_file) as file_stream:
  153. yaml_config = yaml.safe_load(file_stream)
  154. config.update(yaml_config)
  155. pidfile = config["pid_file"]
  156. cache_factor = config.get("synctl_cache_factor")
  157. start_stop_synapse = True
  158. if cache_factor:
  159. os.environ["SYNAPSE_CACHE_FACTOR"] = str(cache_factor)
  160. cache_factors = config.get("synctl_cache_factors", {})
  161. for cache_name, factor in iteritems(cache_factors):
  162. os.environ["SYNAPSE_CACHE_FACTOR_" + cache_name.upper()] = str(factor)
  163. worker_configfiles = []
  164. if options.worker:
  165. start_stop_synapse = False
  166. worker_configfile = options.worker
  167. if not os.path.exists(worker_configfile):
  168. write(
  169. "No worker config found at %r" % (worker_configfile,), stream=sys.stderr
  170. )
  171. sys.exit(1)
  172. worker_configfiles.append(worker_configfile)
  173. if options.all_processes:
  174. # To start the main synapse with -a you need to add a worker file
  175. # with worker_app == "synapse.app.homeserver"
  176. start_stop_synapse = False
  177. worker_configdir = options.all_processes
  178. if not os.path.isdir(worker_configdir):
  179. write(
  180. "No worker config directory found at %r" % (worker_configdir,),
  181. stream=sys.stderr,
  182. )
  183. sys.exit(1)
  184. worker_configfiles.extend(
  185. sorted(glob.glob(os.path.join(worker_configdir, "*.yaml")))
  186. )
  187. workers = []
  188. for worker_configfile in worker_configfiles:
  189. with open(worker_configfile) as stream:
  190. worker_config = yaml.safe_load(stream)
  191. worker_app = worker_config["worker_app"]
  192. if worker_app == "synapse.app.homeserver":
  193. # We need to special case all of this to pick up options that may
  194. # be set in the main config file or in this worker config file.
  195. worker_pidfile = worker_config.get("pid_file") or pidfile
  196. worker_cache_factor = (
  197. worker_config.get("synctl_cache_factor") or cache_factor
  198. )
  199. worker_cache_factors = (
  200. worker_config.get("synctl_cache_factors") or cache_factors
  201. )
  202. daemonize = worker_config.get("daemonize") or config.get("daemonize")
  203. assert daemonize, "Main process must have daemonize set to true"
  204. # The master process doesn't support using worker_* config.
  205. for key in worker_config:
  206. if key == "worker_app": # But we allow worker_app
  207. continue
  208. assert not key.startswith(
  209. "worker_"
  210. ), "Main process cannot use worker_* config"
  211. else:
  212. worker_pidfile = worker_config["worker_pid_file"]
  213. worker_daemonize = worker_config["worker_daemonize"]
  214. assert worker_daemonize, "In config %r: expected '%s' to be True" % (
  215. worker_configfile,
  216. "worker_daemonize",
  217. )
  218. worker_cache_factor = worker_config.get("synctl_cache_factor")
  219. worker_cache_factors = worker_config.get("synctl_cache_factors", {})
  220. workers.append(
  221. Worker(
  222. worker_app,
  223. worker_configfile,
  224. worker_pidfile,
  225. worker_cache_factor,
  226. worker_cache_factors,
  227. )
  228. )
  229. action = options.action
  230. if action == "stop" or action == "restart":
  231. for worker in workers:
  232. stop(worker.pidfile, worker.app)
  233. if start_stop_synapse:
  234. stop(pidfile, "synapse.app.homeserver")
  235. # Wait for synapse to actually shutdown before starting it again
  236. if action == "restart":
  237. running_pids = []
  238. if start_stop_synapse and os.path.exists(pidfile):
  239. running_pids.append(int(open(pidfile).read()))
  240. for worker in workers:
  241. if os.path.exists(worker.pidfile):
  242. running_pids.append(int(open(worker.pidfile).read()))
  243. if len(running_pids) > 0:
  244. write("Waiting for process to exit before restarting...")
  245. for running_pid in running_pids:
  246. while pid_running(running_pid):
  247. time.sleep(0.2)
  248. write("All processes exited; now restarting...")
  249. if action == "start" or action == "restart":
  250. if start_stop_synapse:
  251. # Check if synapse is already running
  252. if os.path.exists(pidfile) and pid_running(int(open(pidfile).read())):
  253. abort("synapse.app.homeserver already running")
  254. start(configfile, bool(options.daemonize))
  255. for worker in workers:
  256. env = os.environ.copy()
  257. if worker.cache_factor:
  258. os.environ["SYNAPSE_CACHE_FACTOR"] = str(worker.cache_factor)
  259. for cache_name, factor in iteritems(worker.cache_factors):
  260. os.environ["SYNAPSE_CACHE_FACTOR_" + cache_name.upper()] = str(factor)
  261. start_worker(worker.app, configfile, worker.configfile)
  262. # Reset env back to the original
  263. os.environ.clear()
  264. os.environ.update(env)
  265. if __name__ == "__main__":
  266. main()