synctl 9.6 KB

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