You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

360 lines
12 KiB

  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, NoReturn, Optional, TextIO
  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. SYNCTL_CACHE_FACTOR_WARNING = """\
  35. Setting 'synctl_cache_factor' in the config is deprecated. Instead, please do
  36. one of the following:
  37. - Either set the environment variable 'SYNAPSE_CACHE_FACTOR'
  38. - or set 'caches.global_factor' in the homeserver config.
  39. --------------------------------------------------------------------------------"""
  40. def pid_running(pid: int) -> bool:
  41. try:
  42. os.kill(pid, 0)
  43. except OSError as err:
  44. if err.errno == errno.EPERM:
  45. pass # process exists
  46. else:
  47. return False
  48. # When running in a container, orphan processes may not get reaped and their
  49. # PIDs may remain valid. Try to work around the issue.
  50. try:
  51. with open(f"/proc/{pid}/status") as status_file:
  52. if "zombie" in status_file.read():
  53. return False
  54. except Exception:
  55. # This isn't Linux or `/proc/` is unavailable.
  56. # Assume that the process is still running.
  57. pass
  58. return True
  59. def write(message: str, colour: str = NORMAL, stream: TextIO = sys.stdout) -> None:
  60. # Lets check if we're writing to a TTY before colouring
  61. should_colour = False
  62. try:
  63. should_colour = stream.isatty()
  64. except AttributeError:
  65. # Just in case `isatty` isn't defined on everything. The python
  66. # docs are incredibly vague.
  67. pass
  68. if not should_colour:
  69. stream.write(message + "\n")
  70. else:
  71. stream.write(colour + message + NORMAL + "\n")
  72. def abort(message: str, colour: str = RED, stream: TextIO = sys.stderr) -> NoReturn:
  73. write(message, colour, stream)
  74. sys.exit(1)
  75. def start(pidfile: str, app: str, config_files: Iterable[str], daemonize: bool) -> bool:
  76. """Attempts to start a synapse main or worker process.
  77. Args:
  78. pidfile: the pidfile we expect the process to create
  79. app: the python module to run
  80. config_files: config files to pass to synapse
  81. daemonize: if True, will include a --daemonize argument to synapse
  82. Returns:
  83. True if the process started successfully or was already running
  84. False if there was an error starting the process
  85. """
  86. if os.path.exists(pidfile) and pid_running(int(open(pidfile).read())):
  87. print(app + " already running")
  88. return True
  89. args = [sys.executable, "-m", app]
  90. for c in config_files:
  91. args += ["-c", c]
  92. if daemonize:
  93. args.append("--daemonize")
  94. try:
  95. subprocess.check_call(args)
  96. write("started %s(%s)" % (app, ",".join(config_files)), colour=GREEN)
  97. return True
  98. except subprocess.CalledProcessError as e:
  99. err = "%s(%s) failed to start (exit code: %d). Check the Synapse logfile" % (
  100. app,
  101. ",".join(config_files),
  102. e.returncode,
  103. )
  104. if daemonize:
  105. err += ", or run synctl with --no-daemonize"
  106. err += "."
  107. write(err, colour=RED, stream=sys.stderr)
  108. return False
  109. def stop(pidfile: str, app: str) -> Optional[int]:
  110. """Attempts to kill a synapse worker from the pidfile.
  111. Args:
  112. pidfile: path to file containing worker's pid
  113. app: name of the worker's appservice
  114. Returns:
  115. process id, or None if the process was not running
  116. """
  117. if os.path.exists(pidfile):
  118. pid = int(open(pidfile).read())
  119. try:
  120. os.kill(pid, signal.SIGTERM)
  121. write("stopped %s" % (app,), colour=GREEN)
  122. return pid
  123. except OSError as err:
  124. if err.errno == errno.ESRCH:
  125. write("%s not running" % (app,), colour=YELLOW)
  126. elif err.errno == errno.EPERM:
  127. abort("Cannot stop %s: Operation not permitted" % (app,))
  128. else:
  129. abort("Cannot stop %s: Unknown error" % (app,))
  130. else:
  131. write(
  132. "No running worker of %s found (from %s)\nThe process might be managed by another controller (e.g. systemd)"
  133. % (app, pidfile),
  134. colour=YELLOW,
  135. )
  136. return None
  137. Worker = collections.namedtuple(
  138. "Worker", ["app", "configfile", "pidfile", "cache_factor", "cache_factors"]
  139. )
  140. def main() -> None:
  141. parser = argparse.ArgumentParser()
  142. parser.add_argument(
  143. "action",
  144. choices=["start", "stop", "restart"],
  145. help="whether to start, stop or restart the synapse",
  146. )
  147. parser.add_argument(
  148. "configfile",
  149. nargs="?",
  150. default="homeserver.yaml",
  151. help="the homeserver config file. Defaults to homeserver.yaml. May also be"
  152. " a directory with *.yaml files",
  153. )
  154. parser.add_argument(
  155. "-w", "--worker", metavar="WORKERCONFIG", help="start or stop a single worker"
  156. )
  157. parser.add_argument(
  158. "-a",
  159. "--all-processes",
  160. metavar="WORKERCONFIGDIR",
  161. help="start or stop all the workers in the given directory"
  162. " and the main synapse process",
  163. )
  164. parser.add_argument(
  165. "--no-daemonize",
  166. action="store_false",
  167. dest="daemonize",
  168. help="Run synapse in the foreground for debugging. "
  169. "Will work only if the daemonize option is not set in the config.",
  170. )
  171. options = parser.parse_args()
  172. if options.worker and options.all_processes:
  173. write('Cannot use "--worker" with "--all-processes"', stream=sys.stderr)
  174. sys.exit(1)
  175. if not options.daemonize and options.all_processes:
  176. write('Cannot use "--no-daemonize" with "--all-processes"', stream=sys.stderr)
  177. sys.exit(1)
  178. configfile = options.configfile
  179. if not os.path.exists(configfile):
  180. write(
  181. f"Config file {configfile} does not exist.\n"
  182. f"To generate a config file, run:\n"
  183. f" {sys.executable} -m {MAIN_PROCESS}"
  184. f" -c {configfile} --generate-config"
  185. f" --server-name=<server name> --report-stats=<yes/no>\n",
  186. stream=sys.stderr,
  187. )
  188. sys.exit(1)
  189. config_files = find_config_files([configfile])
  190. config = {}
  191. for config_file in config_files:
  192. with open(config_file) as file_stream:
  193. yaml_config = yaml.safe_load(file_stream)
  194. if yaml_config is not None:
  195. config.update(yaml_config)
  196. pidfile = config["pid_file"]
  197. cache_factor = config.get("synctl_cache_factor")
  198. start_stop_synapse = True
  199. if cache_factor:
  200. write(SYNCTL_CACHE_FACTOR_WARNING)
  201. os.environ["SYNAPSE_CACHE_FACTOR"] = str(cache_factor)
  202. cache_factors = config.get("synctl_cache_factors", {})
  203. for cache_name, factor in cache_factors.items():
  204. os.environ["SYNAPSE_CACHE_FACTOR_" + cache_name.upper()] = str(factor)
  205. worker_configfiles = []
  206. if options.worker:
  207. start_stop_synapse = False
  208. worker_configfile = options.worker
  209. if not os.path.exists(worker_configfile):
  210. write(
  211. "No worker config found at %r" % (worker_configfile,), stream=sys.stderr
  212. )
  213. sys.exit(1)
  214. worker_configfiles.append(worker_configfile)
  215. if options.all_processes:
  216. # To start the main synapse with -a you need to add a worker file
  217. # with worker_app == "synapse.app.homeserver"
  218. start_stop_synapse = False
  219. worker_configdir = options.all_processes
  220. if not os.path.isdir(worker_configdir):
  221. write(
  222. "No worker config directory found at %r" % (worker_configdir,),
  223. stream=sys.stderr,
  224. )
  225. sys.exit(1)
  226. worker_configfiles.extend(
  227. sorted(glob.glob(os.path.join(worker_configdir, "*.yaml")))
  228. )
  229. workers = []
  230. for worker_configfile in worker_configfiles:
  231. with open(worker_configfile) as stream:
  232. worker_config = yaml.safe_load(stream)
  233. worker_app = worker_config["worker_app"]
  234. if worker_app == "synapse.app.homeserver":
  235. # We need to special case all of this to pick up options that may
  236. # be set in the main config file or in this worker config file.
  237. worker_pidfile = worker_config.get("pid_file") or pidfile
  238. worker_cache_factor = (
  239. worker_config.get("synctl_cache_factor") or cache_factor
  240. )
  241. worker_cache_factors = (
  242. worker_config.get("synctl_cache_factors") or cache_factors
  243. )
  244. # The master process doesn't support using worker_* config.
  245. for key in worker_config:
  246. if key == "worker_app": # But we allow worker_app
  247. continue
  248. assert not key.startswith(
  249. "worker_"
  250. ), "Main process cannot use worker_* config"
  251. else:
  252. worker_pidfile = worker_config["worker_pid_file"]
  253. worker_cache_factor = worker_config.get("synctl_cache_factor")
  254. worker_cache_factors = worker_config.get("synctl_cache_factors", {})
  255. workers.append(
  256. Worker(
  257. worker_app,
  258. worker_configfile,
  259. worker_pidfile,
  260. worker_cache_factor,
  261. worker_cache_factors,
  262. )
  263. )
  264. action = options.action
  265. if action == "stop" or action == "restart":
  266. running_pids = []
  267. for worker in workers:
  268. pid = stop(worker.pidfile, worker.app)
  269. if pid is not None:
  270. running_pids.append(pid)
  271. if start_stop_synapse:
  272. pid = stop(pidfile, MAIN_PROCESS)
  273. if pid is not None:
  274. running_pids.append(pid)
  275. if len(running_pids) > 0:
  276. write("Waiting for processes to exit...")
  277. for running_pid in running_pids:
  278. while pid_running(running_pid):
  279. time.sleep(0.2)
  280. write("All processes exited")
  281. if action == "start" or action == "restart":
  282. error = False
  283. if start_stop_synapse:
  284. if not start(pidfile, MAIN_PROCESS, (configfile,), options.daemonize):
  285. error = True
  286. for worker in workers:
  287. env = os.environ.copy()
  288. if worker.cache_factor:
  289. os.environ["SYNAPSE_CACHE_FACTOR"] = str(worker.cache_factor)
  290. for cache_name, factor in worker.cache_factors.items():
  291. os.environ["SYNAPSE_CACHE_FACTOR_" + cache_name.upper()] = str(factor)
  292. if not start(
  293. worker.pidfile,
  294. worker.app,
  295. (configfile, worker.configfile),
  296. options.daemonize,
  297. ):
  298. error = True
  299. # Reset env back to the original
  300. os.environ.clear()
  301. os.environ.update(env)
  302. if error:
  303. exit(1)
  304. if __name__ == "__main__":
  305. main()