1
0

synctl 10 KB

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