synctl.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2014-2016 OpenMarket 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. import yaml
  27. SYNAPSE = [sys.executable, "-B", "-m", "synapse.app.homeserver"]
  28. GREEN = "\x1b[1;32m"
  29. YELLOW = "\x1b[1;33m"
  30. RED = "\x1b[1;31m"
  31. NORMAL = "\x1b[m"
  32. def pid_running(pid):
  33. try:
  34. os.kill(pid, 0)
  35. return True
  36. except OSError as err:
  37. if err.errno == errno.EPERM:
  38. return True
  39. return False
  40. def write(message, colour=NORMAL, stream=sys.stdout):
  41. if colour == NORMAL:
  42. stream.write(message + "\n")
  43. else:
  44. stream.write(colour + message + NORMAL + "\n")
  45. def abort(message, colour=RED, stream=sys.stderr):
  46. write(message, colour, stream)
  47. sys.exit(1)
  48. def start(configfile):
  49. write("Starting ...")
  50. args = SYNAPSE
  51. args.extend(["--daemonize", "-c", configfile])
  52. try:
  53. subprocess.check_call(args)
  54. write("started synapse.app.homeserver(%r)" %
  55. (configfile,), colour=GREEN)
  56. except subprocess.CalledProcessError as e:
  57. write(
  58. "error starting (exit code: %d); see above for logs" % e.returncode,
  59. colour=RED,
  60. )
  61. def start_worker(app, configfile, worker_configfile):
  62. args = [
  63. "python", "-B",
  64. "-m", app,
  65. "-c", configfile,
  66. "-c", worker_configfile
  67. ]
  68. try:
  69. subprocess.check_call(args)
  70. write("started %s(%r)" % (app, worker_configfile), colour=GREEN)
  71. except subprocess.CalledProcessError as e:
  72. write(
  73. "error starting %s(%r) (exit code: %d); see above for logs" % (
  74. app, worker_configfile, e.returncode,
  75. ),
  76. colour=RED,
  77. )
  78. def stop(pidfile, app):
  79. if os.path.exists(pidfile):
  80. pid = int(open(pidfile).read())
  81. try:
  82. os.kill(pid, signal.SIGTERM)
  83. write("stopped %s" % (app,), colour=GREEN)
  84. except OSError as err:
  85. if err.errno == errno.ESRCH:
  86. write("%s not running" % (app,), colour=YELLOW)
  87. elif err.errno == errno.EPERM:
  88. abort("Cannot stop %s: Operation not permitted" % (app,))
  89. else:
  90. abort("Cannot stop %s: Unknown error" % (app,))
  91. Worker = collections.namedtuple("Worker", [
  92. "app", "configfile", "pidfile", "cache_factor"
  93. ])
  94. def main():
  95. parser = argparse.ArgumentParser()
  96. parser.add_argument(
  97. "action",
  98. choices=["start", "stop", "restart"],
  99. help="whether to start, stop or restart the synapse",
  100. )
  101. parser.add_argument(
  102. "configfile",
  103. nargs="?",
  104. default="homeserver.yaml",
  105. help="the homeserver config file, defaults to homeserver.yaml",
  106. )
  107. parser.add_argument(
  108. "-w", "--worker",
  109. metavar="WORKERCONFIG",
  110. help="start or stop a single worker",
  111. )
  112. parser.add_argument(
  113. "-a", "--all-processes",
  114. metavar="WORKERCONFIGDIR",
  115. help="start or stop all the workers in the given directory"
  116. " and the main synapse process",
  117. )
  118. options = parser.parse_args()
  119. if options.worker and options.all_processes:
  120. write(
  121. 'Cannot use "--worker" with "--all-processes"',
  122. stream=sys.stderr
  123. )
  124. sys.exit(1)
  125. configfile = options.configfile
  126. if not os.path.exists(configfile):
  127. write(
  128. "No config file found\n"
  129. "To generate a config file, run '%s -c %s --generate-config"
  130. " --server-name=<server name>'\n" % (
  131. " ".join(SYNAPSE), options.configfile
  132. ),
  133. stream=sys.stderr,
  134. )
  135. sys.exit(1)
  136. with open(configfile) as stream:
  137. config = yaml.load(stream)
  138. pidfile = config["pid_file"]
  139. cache_factor = config.get("synctl_cache_factor")
  140. start_stop_synapse = True
  141. if cache_factor:
  142. os.environ["SYNAPSE_CACHE_FACTOR"] = str(cache_factor)
  143. cache_factors = config.get("synctl_cache_factors", {})
  144. for cache_name, factor in cache_factors.iteritems():
  145. os.environ["SYNAPSE_CACHE_FACTOR_" + cache_name.upper()] = str(factor)
  146. worker_configfiles = []
  147. if options.worker:
  148. start_stop_synapse = False
  149. worker_configfile = options.worker
  150. if not os.path.exists(worker_configfile):
  151. write(
  152. "No worker config found at %r" % (worker_configfile,),
  153. stream=sys.stderr,
  154. )
  155. sys.exit(1)
  156. worker_configfiles.append(worker_configfile)
  157. if options.all_processes:
  158. # To start the main synapse with -a you need to add a worker file
  159. # with worker_app == "synapse.app.homeserver"
  160. start_stop_synapse = False
  161. worker_configdir = options.all_processes
  162. if not os.path.isdir(worker_configdir):
  163. write(
  164. "No worker config directory found at %r" % (worker_configdir,),
  165. stream=sys.stderr,
  166. )
  167. sys.exit(1)
  168. worker_configfiles.extend(sorted(glob.glob(
  169. os.path.join(worker_configdir, "*.yaml")
  170. )))
  171. workers = []
  172. for worker_configfile in worker_configfiles:
  173. with open(worker_configfile) as stream:
  174. worker_config = yaml.load(stream)
  175. worker_app = worker_config["worker_app"]
  176. if worker_app == "synapse.app.homeserver":
  177. # We need to special case all of this to pick up options that may
  178. # be set in the main config file or in this worker config file.
  179. worker_pidfile = (
  180. worker_config.get("pid_file")
  181. or pidfile
  182. )
  183. worker_cache_factor = worker_config.get("synctl_cache_factor") or cache_factor
  184. daemonize = worker_config.get("daemonize") or config.get("daemonize")
  185. assert daemonize, "Main process must have daemonize set to true"
  186. # The master process doesn't support using worker_* config.
  187. for key in worker_config:
  188. if key == "worker_app": # But we allow worker_app
  189. continue
  190. assert not key.startswith("worker_"), \
  191. "Main process cannot use worker_* config"
  192. else:
  193. worker_pidfile = worker_config["worker_pid_file"]
  194. worker_daemonize = worker_config["worker_daemonize"]
  195. assert worker_daemonize, "In config %r: expected '%s' to be True" % (
  196. worker_configfile, "worker_daemonize")
  197. worker_cache_factor = worker_config.get("synctl_cache_factor")
  198. workers.append(Worker(
  199. worker_app, worker_configfile, worker_pidfile, worker_cache_factor,
  200. ))
  201. action = options.action
  202. if action == "stop" or action == "restart":
  203. for worker in workers:
  204. stop(worker.pidfile, worker.app)
  205. if start_stop_synapse:
  206. stop(pidfile, "synapse.app.homeserver")
  207. # Wait for synapse to actually shutdown before starting it again
  208. if action == "restart":
  209. running_pids = []
  210. if start_stop_synapse and os.path.exists(pidfile):
  211. running_pids.append(int(open(pidfile).read()))
  212. for worker in workers:
  213. if os.path.exists(worker.pidfile):
  214. running_pids.append(int(open(worker.pidfile).read()))
  215. if len(running_pids) > 0:
  216. write("Waiting for process to exit before restarting...")
  217. for running_pid in running_pids:
  218. while pid_running(running_pid):
  219. time.sleep(0.2)
  220. write("All processes exited; now restarting...")
  221. if action == "start" or action == "restart":
  222. if start_stop_synapse:
  223. # Check if synapse is already running
  224. if os.path.exists(pidfile) and pid_running(int(open(pidfile).read())):
  225. abort("synapse.app.homeserver already running")
  226. start(configfile)
  227. for worker in workers:
  228. if worker.cache_factor:
  229. os.environ["SYNAPSE_CACHE_FACTOR"] = str(worker.cache_factor)
  230. start_worker(worker.app, configfile, worker.configfile)
  231. if cache_factor:
  232. os.environ["SYNAPSE_CACHE_FACTOR"] = str(cache_factor)
  233. else:
  234. os.environ.pop("SYNAPSE_CACHE_FACTOR", None)
  235. if __name__ == "__main__":
  236. main()