synctl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. #!/usr/bin/env python
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import argparse
  17. import collections
  18. import errno
  19. import glob
  20. import os
  21. import os.path
  22. import signal
  23. import subprocess
  24. import sys
  25. import time
  26. from typing import Iterable, Optional
  27. import yaml
  28. from synapse.config import find_config_files
  29. MAIN_PROCESS = "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. except OSError as err:
  38. if err.errno == errno.EPERM:
  39. pass # process exists
  40. else:
  41. return False
  42. # When running in a container, orphan processes may not get reaped and their
  43. # PIDs may remain valid. Try to work around the issue.
  44. try:
  45. with open(f"/proc/{pid}/status") as status_file:
  46. if "zombie" in status_file.read():
  47. return False
  48. except Exception:
  49. # This isn't Linux or `/proc/` is unavailable.
  50. # Assume that the process is still running.
  51. pass
  52. return True
  53. def write(message, colour=NORMAL, stream=sys.stdout):
  54. # Lets check if we're writing to a TTY before colouring
  55. should_colour = False
  56. try:
  57. should_colour = stream.isatty()
  58. except AttributeError:
  59. # Just in case `isatty` isn't defined on everything. The python
  60. # docs are incredibly vague.
  61. pass
  62. if not should_colour:
  63. stream.write(message + "\n")
  64. else:
  65. stream.write(colour + message + NORMAL + "\n")
  66. def abort(message, colour=RED, stream=sys.stderr):
  67. write(message, colour, stream)
  68. sys.exit(1)
  69. def start(pidfile: str, app: str, config_files: Iterable[str], daemonize: bool) -> bool:
  70. """Attempts to start a synapse main or worker process.
  71. Args:
  72. pidfile: the pidfile we expect the process to create
  73. app: the python module to run
  74. config_files: config files to pass to synapse
  75. daemonize: if True, will include a --daemonize argument to synapse
  76. Returns:
  77. True if the process started successfully or was already running
  78. False if there was an error starting the process
  79. """
  80. if os.path.exists(pidfile) and pid_running(int(open(pidfile).read())):
  81. print(app + " already running")
  82. return True
  83. args = [sys.executable, "-m", app]
  84. for c in config_files:
  85. args += ["-c", c]
  86. if daemonize:
  87. args.append("--daemonize")
  88. try:
  89. subprocess.check_call(args)
  90. write("started %s(%s)" % (app, ",".join(config_files)), colour=GREEN)
  91. return True
  92. except subprocess.CalledProcessError as e:
  93. err = "%s(%s) failed to start (exit code: %d). Check the Synapse logfile" % (
  94. app,
  95. ",".join(config_files),
  96. e.returncode,
  97. )
  98. if daemonize:
  99. err += ", or run synctl with --no-daemonize"
  100. err += "."
  101. write(err, colour=RED, stream=sys.stderr)
  102. return False
  103. def stop(pidfile: str, app: str) -> Optional[int]:
  104. """Attempts to kill a synapse worker from the pidfile.
  105. Args:
  106. pidfile: path to file containing worker's pid
  107. app: name of the worker's appservice
  108. Returns:
  109. process id, or None if the process was not running
  110. """
  111. if os.path.exists(pidfile):
  112. pid = int(open(pidfile).read())
  113. try:
  114. os.kill(pid, signal.SIGTERM)
  115. write("stopped %s" % (app,), colour=GREEN)
  116. return pid
  117. except OSError as err:
  118. if err.errno == errno.ESRCH:
  119. write("%s not running" % (app,), colour=YELLOW)
  120. elif err.errno == errno.EPERM:
  121. abort("Cannot stop %s: Operation not permitted" % (app,))
  122. else:
  123. abort("Cannot stop %s: Unknown error" % (app,))
  124. else:
  125. write(
  126. "No running worker of %s found (from %s)\nThe process might be managed by another controller (e.g. systemd)"
  127. % (app, pidfile),
  128. colour=YELLOW,
  129. )
  130. return None
  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. f"Config file {configfile} does not exist.\n"
  176. f"To generate a config file, run:\n"
  177. f" {sys.executable} -m {MAIN_PROCESS}"
  178. f" -c {configfile} --generate-config"
  179. f" --server-name=<server name> --report-stats=<yes/no>\n",
  180. stream=sys.stderr,
  181. )
  182. sys.exit(1)
  183. config_files = find_config_files([configfile])
  184. config = {}
  185. for config_file in config_files:
  186. with open(config_file) as file_stream:
  187. yaml_config = yaml.safe_load(file_stream)
  188. if yaml_config is not None:
  189. config.update(yaml_config)
  190. pidfile = config["pid_file"]
  191. cache_factor = config.get("synctl_cache_factor")
  192. start_stop_synapse = True
  193. if cache_factor:
  194. os.environ["SYNAPSE_CACHE_FACTOR"] = str(cache_factor)
  195. cache_factors = config.get("synctl_cache_factors", {})
  196. for cache_name, factor in cache_factors.items():
  197. os.environ["SYNAPSE_CACHE_FACTOR_" + cache_name.upper()] = str(factor)
  198. worker_configfiles = []
  199. if options.worker:
  200. start_stop_synapse = False
  201. worker_configfile = options.worker
  202. if not os.path.exists(worker_configfile):
  203. write(
  204. "No worker config found at %r" % (worker_configfile,), stream=sys.stderr
  205. )
  206. sys.exit(1)
  207. worker_configfiles.append(worker_configfile)
  208. if options.all_processes:
  209. # To start the main synapse with -a you need to add a worker file
  210. # with worker_app == "synapse.app.homeserver"
  211. start_stop_synapse = False
  212. worker_configdir = options.all_processes
  213. if not os.path.isdir(worker_configdir):
  214. write(
  215. "No worker config directory found at %r" % (worker_configdir,),
  216. stream=sys.stderr,
  217. )
  218. sys.exit(1)
  219. worker_configfiles.extend(
  220. sorted(glob.glob(os.path.join(worker_configdir, "*.yaml")))
  221. )
  222. workers = []
  223. for worker_configfile in worker_configfiles:
  224. with open(worker_configfile) as stream:
  225. worker_config = yaml.safe_load(stream)
  226. worker_app = worker_config["worker_app"]
  227. if worker_app == "synapse.app.homeserver":
  228. # We need to special case all of this to pick up options that may
  229. # be set in the main config file or in this worker config file.
  230. worker_pidfile = worker_config.get("pid_file") or pidfile
  231. worker_cache_factor = (
  232. worker_config.get("synctl_cache_factor") or cache_factor
  233. )
  234. worker_cache_factors = (
  235. worker_config.get("synctl_cache_factors") or cache_factors
  236. )
  237. # The master process doesn't support using worker_* config.
  238. for key in worker_config:
  239. if key == "worker_app": # But we allow worker_app
  240. continue
  241. assert not key.startswith(
  242. "worker_"
  243. ), "Main process cannot use worker_* config"
  244. else:
  245. worker_pidfile = worker_config["worker_pid_file"]
  246. worker_cache_factor = worker_config.get("synctl_cache_factor")
  247. worker_cache_factors = worker_config.get("synctl_cache_factors", {})
  248. workers.append(
  249. Worker(
  250. worker_app,
  251. worker_configfile,
  252. worker_pidfile,
  253. worker_cache_factor,
  254. worker_cache_factors,
  255. )
  256. )
  257. action = options.action
  258. if action == "stop" or action == "restart":
  259. running_pids = []
  260. for worker in workers:
  261. pid = stop(worker.pidfile, worker.app)
  262. if pid is not None:
  263. running_pids.append(pid)
  264. if start_stop_synapse:
  265. pid = stop(pidfile, MAIN_PROCESS)
  266. if pid is not None:
  267. running_pids.append(pid)
  268. if len(running_pids) > 0:
  269. write("Waiting for processes to exit...")
  270. for running_pid in running_pids:
  271. while pid_running(running_pid):
  272. time.sleep(0.2)
  273. write("All processes exited")
  274. if action == "start" or action == "restart":
  275. error = False
  276. if start_stop_synapse:
  277. if not start(pidfile, MAIN_PROCESS, (configfile,), options.daemonize):
  278. error = True
  279. for worker in workers:
  280. env = os.environ.copy()
  281. if worker.cache_factor:
  282. os.environ["SYNAPSE_CACHE_FACTOR"] = str(worker.cache_factor)
  283. for cache_name, factor in worker.cache_factors.items():
  284. os.environ["SYNAPSE_CACHE_FACTOR_" + cache_name.upper()] = str(factor)
  285. if not start(
  286. worker.pidfile,
  287. worker.app,
  288. (configfile, worker.configfile),
  289. options.daemonize,
  290. ):
  291. error = True
  292. # Reset env back to the original
  293. os.environ.clear()
  294. os.environ.update(env)
  295. if error:
  296. exit(1)
  297. if __name__ == "__main__":
  298. main()