synctl 11 KB

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