synctl 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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>'\n" % (" ".join(SYNAPSE), options.configfile),
  130. stream=sys.stderr,
  131. )
  132. sys.exit(1)
  133. with open(configfile) as stream:
  134. config = yaml.load(stream)
  135. pidfile = config["pid_file"]
  136. cache_factor = config.get("synctl_cache_factor")
  137. start_stop_synapse = True
  138. if cache_factor:
  139. os.environ["SYNAPSE_CACHE_FACTOR"] = str(cache_factor)
  140. cache_factors = config.get("synctl_cache_factors", {})
  141. for cache_name, factor in iteritems(cache_factors):
  142. os.environ["SYNAPSE_CACHE_FACTOR_" + cache_name.upper()] = str(factor)
  143. worker_configfiles = []
  144. if options.worker:
  145. start_stop_synapse = False
  146. worker_configfile = options.worker
  147. if not os.path.exists(worker_configfile):
  148. write(
  149. "No worker config found at %r" % (worker_configfile,), stream=sys.stderr
  150. )
  151. sys.exit(1)
  152. worker_configfiles.append(worker_configfile)
  153. if options.all_processes:
  154. # To start the main synapse with -a you need to add a worker file
  155. # with worker_app == "synapse.app.homeserver"
  156. start_stop_synapse = False
  157. worker_configdir = options.all_processes
  158. if not os.path.isdir(worker_configdir):
  159. write(
  160. "No worker config directory found at %r" % (worker_configdir,),
  161. stream=sys.stderr,
  162. )
  163. sys.exit(1)
  164. worker_configfiles.extend(
  165. sorted(glob.glob(os.path.join(worker_configdir, "*.yaml")))
  166. )
  167. workers = []
  168. for worker_configfile in worker_configfiles:
  169. with open(worker_configfile) as stream:
  170. worker_config = yaml.load(stream)
  171. worker_app = worker_config["worker_app"]
  172. if worker_app == "synapse.app.homeserver":
  173. # We need to special case all of this to pick up options that may
  174. # be set in the main config file or in this worker config file.
  175. worker_pidfile = worker_config.get("pid_file") or pidfile
  176. worker_cache_factor = (
  177. worker_config.get("synctl_cache_factor") or cache_factor
  178. )
  179. worker_cache_factors = (
  180. worker_config.get("synctl_cache_factors") or cache_factors
  181. )
  182. daemonize = worker_config.get("daemonize") or config.get("daemonize")
  183. assert daemonize, "Main process must have daemonize set to true"
  184. # The master process doesn't support using worker_* config.
  185. for key in worker_config:
  186. if key == "worker_app": # But we allow worker_app
  187. continue
  188. assert not key.startswith(
  189. "worker_"
  190. ), "Main process cannot use worker_* config"
  191. else:
  192. worker_pidfile = worker_config["worker_pid_file"]
  193. worker_daemonize = worker_config["worker_daemonize"]
  194. assert worker_daemonize, "In config %r: expected '%s' to be True" % (
  195. worker_configfile,
  196. "worker_daemonize",
  197. )
  198. worker_cache_factor = worker_config.get("synctl_cache_factor")
  199. worker_cache_factors = worker_config.get("synctl_cache_factors", {})
  200. workers.append(
  201. Worker(
  202. worker_app,
  203. worker_configfile,
  204. worker_pidfile,
  205. worker_cache_factor,
  206. worker_cache_factors,
  207. )
  208. )
  209. action = options.action
  210. if action == "stop" or action == "restart":
  211. for worker in workers:
  212. stop(worker.pidfile, worker.app)
  213. if start_stop_synapse:
  214. stop(pidfile, "synapse.app.homeserver")
  215. # Wait for synapse to actually shutdown before starting it again
  216. if action == "restart":
  217. running_pids = []
  218. if start_stop_synapse and os.path.exists(pidfile):
  219. running_pids.append(int(open(pidfile).read()))
  220. for worker in workers:
  221. if os.path.exists(worker.pidfile):
  222. running_pids.append(int(open(worker.pidfile).read()))
  223. if len(running_pids) > 0:
  224. write("Waiting for process to exit before restarting...")
  225. for running_pid in running_pids:
  226. while pid_running(running_pid):
  227. time.sleep(0.2)
  228. write("All processes exited; now restarting...")
  229. if action == "start" or action == "restart":
  230. if start_stop_synapse:
  231. # Check if synapse is already running
  232. if os.path.exists(pidfile) and pid_running(int(open(pidfile).read())):
  233. abort("synapse.app.homeserver already running")
  234. start(configfile)
  235. for worker in workers:
  236. env = os.environ.copy()
  237. if worker.cache_factor:
  238. os.environ["SYNAPSE_CACHE_FACTOR"] = str(worker.cache_factor)
  239. for cache_name, factor in iteritems(worker.cache_factors):
  240. os.environ["SYNAPSE_CACHE_FACTOR_" + cache_name.upper()] = str(factor)
  241. start_worker(worker.app, configfile, worker.configfile)
  242. # Reset env back to the original
  243. os.environ.clear()
  244. os.environ.update(env)
  245. if __name__ == "__main__":
  246. main()