1
0

synctl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. import yaml
  28. from synapse.config import find_config_files
  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: str, daemonize: bool = True) -> bool:
  59. """Attempts to start synapse.
  60. Args:
  61. configfile: path to a yaml synapse config file
  62. daemonize: whether to daemonize synapse or keep it attached to the current
  63. session
  64. Returns:
  65. True if the process started successfully
  66. False if there was an error starting the process
  67. If deamonize is False it will only return once synapse exits.
  68. """
  69. write("Starting ...")
  70. args = SYNAPSE
  71. if daemonize:
  72. args.extend(["--daemonize", "-c", configfile])
  73. else:
  74. args.extend(["-c", configfile])
  75. try:
  76. subprocess.check_call(args)
  77. write("started synapse.app.homeserver(%r)" % (configfile,), colour=GREEN)
  78. return True
  79. except subprocess.CalledProcessError as e:
  80. write(
  81. "error starting (exit code: %d); see above for logs" % e.returncode,
  82. colour=RED,
  83. )
  84. return False
  85. def start_worker(app: str, configfile: str, worker_configfile: str) -> bool:
  86. """Attempts to start a synapse worker.
  87. Args:
  88. app: name of the worker's appservice
  89. configfile: path to a yaml synapse config file
  90. worker_configfile: path to worker specific yaml synapse file
  91. Returns:
  92. True if the process started successfully
  93. False if there was an error starting the process
  94. """
  95. args = [
  96. sys.executable,
  97. "-B",
  98. "-m",
  99. app,
  100. "-c",
  101. configfile,
  102. "-c",
  103. worker_configfile,
  104. "--daemonize",
  105. ]
  106. try:
  107. subprocess.check_call(args)
  108. write("started %s(%r)" % (app, worker_configfile), colour=GREEN)
  109. return True
  110. except subprocess.CalledProcessError as e:
  111. write(
  112. "error starting %s(%r) (exit code: %d); see above for logs"
  113. % (app, worker_configfile, e.returncode),
  114. colour=RED,
  115. )
  116. return False
  117. def stop(pidfile: str, app: str) -> bool:
  118. """Attempts to kill a synapse worker from the pidfile.
  119. Args:
  120. pidfile: path to file containing worker's pid
  121. app: name of the worker's appservice
  122. Returns:
  123. True if the process stopped successfully
  124. False if process was already stopped or an error occured
  125. """
  126. if os.path.exists(pidfile):
  127. pid = int(open(pidfile).read())
  128. try:
  129. os.kill(pid, signal.SIGTERM)
  130. write("stopped %s" % (app,), colour=GREEN)
  131. return True
  132. except OSError as err:
  133. if err.errno == errno.ESRCH:
  134. write("%s not running" % (app,), colour=YELLOW)
  135. elif err.errno == errno.EPERM:
  136. abort("Cannot stop %s: Operation not permitted" % (app,))
  137. else:
  138. abort("Cannot stop %s: Unknown error" % (app,))
  139. return False
  140. else:
  141. write(
  142. "No running worker of %s found (from %s)\nThe process might be managed by another controller (e.g. systemd)"
  143. % (app, pidfile),
  144. colour=YELLOW,
  145. )
  146. return False
  147. Worker = collections.namedtuple(
  148. "Worker", ["app", "configfile", "pidfile", "cache_factor", "cache_factors"]
  149. )
  150. def main():
  151. parser = argparse.ArgumentParser()
  152. parser.add_argument(
  153. "action",
  154. choices=["start", "stop", "restart"],
  155. help="whether to start, stop or restart the synapse",
  156. )
  157. parser.add_argument(
  158. "configfile",
  159. nargs="?",
  160. default="homeserver.yaml",
  161. help="the homeserver config file. Defaults to homeserver.yaml. May also be"
  162. " a directory with *.yaml files",
  163. )
  164. parser.add_argument(
  165. "-w", "--worker", metavar="WORKERCONFIG", help="start or stop a single worker"
  166. )
  167. parser.add_argument(
  168. "-a",
  169. "--all-processes",
  170. metavar="WORKERCONFIGDIR",
  171. help="start or stop all the workers in the given directory"
  172. " and the main synapse process",
  173. )
  174. parser.add_argument(
  175. "--no-daemonize",
  176. action="store_false",
  177. dest="daemonize",
  178. help="Run synapse in the foreground for debugging. "
  179. "Will work only if the daemonize option is not set in the config.",
  180. )
  181. options = parser.parse_args()
  182. if options.worker and options.all_processes:
  183. write('Cannot use "--worker" with "--all-processes"', stream=sys.stderr)
  184. sys.exit(1)
  185. if not options.daemonize and options.all_processes:
  186. write('Cannot use "--no-daemonize" with "--all-processes"', stream=sys.stderr)
  187. sys.exit(1)
  188. configfile = options.configfile
  189. if not os.path.exists(configfile):
  190. write(
  191. "No config file found\n"
  192. "To generate a config file, run '%s -c %s --generate-config"
  193. " --server-name=<server name> --report-stats=<yes/no>'\n"
  194. % (" ".join(SYNAPSE), options.configfile),
  195. stream=sys.stderr,
  196. )
  197. sys.exit(1)
  198. config_files = find_config_files([configfile])
  199. config = {}
  200. for config_file in config_files:
  201. with open(config_file) as file_stream:
  202. yaml_config = yaml.safe_load(file_stream)
  203. if yaml_config is not None:
  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 cache_factors.items():
  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 worker.cache_factors.items():
  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()