1
0

synctl 11 KB

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