1
0

synctl 12 KB

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