synctl 9.3 KB

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