Development of an internal social media platform with personalised dashboards for students
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.

runzeo.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2001, 2002, 2003 Zope Foundation and Contributors.
  4. # All Rights Reserved.
  5. #
  6. # This software is subject to the provisions of the Zope Public License,
  7. # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
  8. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  9. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  10. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  11. # FOR A PARTICULAR PURPOSE
  12. #
  13. ##############################################################################
  14. """Start the ZEO storage server.
  15. Usage: %s [-C URL] [-a ADDRESS] [-f FILENAME] [-h]
  16. Options:
  17. -C/--configuration URL -- configuration file or URL
  18. -a/--address ADDRESS -- server address of the form PORT, HOST:PORT, or PATH
  19. (a PATH must contain at least one "/")
  20. -f/--filename FILENAME -- filename for FileStorage
  21. -t/--timeout TIMEOUT -- transaction timeout in seconds (default no timeout)
  22. -h/--help -- print this usage message and exit
  23. --pid-file PATH -- relative path to output file containing this process's pid;
  24. default $(INSTANCE_HOME)/var/ZEO.pid but only if envar
  25. INSTANCE_HOME is defined
  26. Unless -C is specified, -a and -f are required.
  27. """
  28. from __future__ import print_function
  29. # The code here is designed to be reused by other, similar servers.
  30. import os
  31. import sys
  32. import signal
  33. import socket
  34. import logging
  35. import six
  36. import ZConfig.datatypes
  37. from zdaemon.zdoptions import ZDOptions
  38. logger = logging.getLogger('ZEO.runzeo')
  39. _pid = str(os.getpid())
  40. def log(msg, level=logging.INFO, exc_info=False):
  41. """Internal: generic logging function."""
  42. message = "(%s) %s" % (_pid, msg)
  43. logger.log(level, message, exc_info=exc_info)
  44. def parse_binding_address(arg):
  45. # Caution: Not part of the official ZConfig API.
  46. obj = ZConfig.datatypes.SocketBindingAddress(arg)
  47. return obj.family, obj.address
  48. def windows_shutdown_handler():
  49. # Called by the signal mechanism on Windows to perform shutdown.
  50. import asyncore
  51. asyncore.close_all()
  52. class ZEOOptionsMixin(object):
  53. storages = None
  54. def handle_address(self, arg):
  55. self.family, self.address = parse_binding_address(arg)
  56. def handle_filename(self, arg):
  57. from ZODB.config import FileStorage # That's a FileStorage *opener*!
  58. class FSConfig(object):
  59. def __init__(self, name, path):
  60. self._name = name
  61. self.path = path
  62. self.stop = None
  63. def getSectionName(self):
  64. return self._name
  65. if not self.storages:
  66. self.storages = []
  67. name = str(1 + len(self.storages))
  68. conf = FileStorage(FSConfig(name, arg))
  69. self.storages.append(conf)
  70. testing_exit_immediately = False
  71. def handle_test(self, *args):
  72. self.testing_exit_immediately = True
  73. def add_zeo_options(self):
  74. self.add(None, None, None, "test", self.handle_test)
  75. self.add(None, None, "a:", "address=", self.handle_address)
  76. self.add(None, None, "f:", "filename=", self.handle_filename)
  77. self.add("family", "zeo.address.family")
  78. self.add("address", "zeo.address.address",
  79. required="no server address specified; use -a or -C")
  80. self.add("read_only", "zeo.read_only", default=0)
  81. self.add("client_conflict_resolution",
  82. "zeo.client_conflict_resolution",
  83. default=0)
  84. self.add("msgpack", "zeo.msgpack", default=0)
  85. self.add("invalidation_queue_size", "zeo.invalidation_queue_size",
  86. default=100)
  87. self.add("invalidation_age", "zeo.invalidation_age")
  88. self.add("transaction_timeout", "zeo.transaction_timeout",
  89. "t:", "timeout=", float)
  90. self.add('pid_file', 'zeo.pid_filename',
  91. None, 'pid-file=')
  92. self.add("ssl", "zeo.ssl")
  93. class ZEOOptions(ZDOptions, ZEOOptionsMixin):
  94. __doc__ = __doc__
  95. logsectionname = "eventlog"
  96. schemadir = os.path.dirname(__file__)
  97. def __init__(self):
  98. ZDOptions.__init__(self)
  99. self.add_zeo_options()
  100. self.add("storages", "storages",
  101. required="no storages specified; use -f or -C")
  102. def realize(self, *a, **k):
  103. ZDOptions.realize(self, *a, **k)
  104. nunnamed = [s for s in self.storages if s.name is None]
  105. if nunnamed:
  106. if len(nunnamed) > 1:
  107. return self.usage("No more than one storage may be unnamed.")
  108. if [s for s in self.storages if s.name == '1']:
  109. return self.usage(
  110. "Can't have an unnamed storage and a storage named 1.")
  111. for s in self.storages:
  112. if s.name is None:
  113. s.name = '1'
  114. break
  115. class ZEOServer(object):
  116. def __init__(self, options):
  117. self.options = options
  118. self.server = None
  119. def main(self):
  120. self.setup_default_logging()
  121. self.check_socket()
  122. self.clear_socket()
  123. self.make_pidfile()
  124. try:
  125. self.open_storages()
  126. self.setup_signals()
  127. self.create_server()
  128. self.loop_forever()
  129. finally:
  130. self.close_server()
  131. self.clear_socket()
  132. self.remove_pidfile()
  133. def setup_default_logging(self):
  134. if self.options.config_logger is not None:
  135. return
  136. # No log file is configured; default to stderr.
  137. root = logging.getLogger()
  138. root.setLevel(logging.INFO)
  139. fmt = logging.Formatter(
  140. "------\n%(asctime)s %(levelname)s %(name)s %(message)s",
  141. "%Y-%m-%dT%H:%M:%S")
  142. handler = logging.StreamHandler()
  143. handler.setFormatter(fmt)
  144. root.addHandler(handler)
  145. def check_socket(self):
  146. if (isinstance(self.options.address, tuple) and
  147. self.options.address[1] is None):
  148. self.options.address = self.options.address[0], 0
  149. return
  150. if self.can_connect(self.options.family, self.options.address):
  151. self.options.usage("address %s already in use" %
  152. repr(self.options.address))
  153. def can_connect(self, family, address):
  154. s = socket.socket(family, socket.SOCK_STREAM)
  155. try:
  156. s.connect(address)
  157. except socket.error:
  158. return 0
  159. else:
  160. s.close()
  161. return 1
  162. def clear_socket(self):
  163. if isinstance(self.options.address, six.string_types):
  164. try:
  165. os.unlink(self.options.address)
  166. except os.error:
  167. pass
  168. def open_storages(self):
  169. self.storages = {}
  170. for opener in self.options.storages:
  171. log("opening storage %r using %s"
  172. % (opener.name, opener.__class__.__name__))
  173. self.storages[opener.name] = opener.open()
  174. def setup_signals(self):
  175. """Set up signal handlers.
  176. The signal handler for SIGFOO is a method handle_sigfoo().
  177. If no handler method is defined for a signal, the signal
  178. action is not changed from its initial value. The handler
  179. method is called without additional arguments.
  180. """
  181. if os.name != "posix":
  182. if os.name == "nt":
  183. self.setup_win32_signals()
  184. return
  185. if hasattr(signal, 'SIGXFSZ'):
  186. signal.signal(signal.SIGXFSZ, signal.SIG_IGN) # Special case
  187. init_signames()
  188. for sig, name in signames.items():
  189. method = getattr(self, "handle_" + name.lower(), None)
  190. if method is not None:
  191. def wrapper(sig_dummy, frame_dummy, method=method):
  192. method()
  193. signal.signal(sig, wrapper)
  194. def setup_win32_signals(self):
  195. # Borrow the Zope Signals package win32 support, if available.
  196. # Signals does a check/log for the availability of pywin32.
  197. try:
  198. import Signals.Signals
  199. except ImportError:
  200. logger.debug("Signals package not found. "
  201. "Windows-specific signal handler "
  202. "will *not* be installed.")
  203. return
  204. SignalHandler = Signals.Signals.SignalHandler
  205. if SignalHandler is not None: # may be None if no pywin32.
  206. SignalHandler.registerHandler(signal.SIGTERM,
  207. windows_shutdown_handler)
  208. SignalHandler.registerHandler(signal.SIGINT,
  209. windows_shutdown_handler)
  210. SIGUSR2 = 12 # not in signal module on Windows.
  211. SignalHandler.registerHandler(SIGUSR2, self.handle_sigusr2)
  212. def create_server(self):
  213. self.server = create_server(self.storages, self.options)
  214. def loop_forever(self):
  215. if self.options.testing_exit_immediately:
  216. print("testing exit immediately")
  217. else:
  218. self.server.loop()
  219. def close_server(self):
  220. if self.server is not None:
  221. self.server.close()
  222. def handle_sigterm(self):
  223. log("terminated by SIGTERM")
  224. sys.exit(0)
  225. def handle_sigint(self):
  226. log("terminated by SIGINT")
  227. sys.exit(0)
  228. def handle_sighup(self):
  229. log("restarted by SIGHUP")
  230. sys.exit(1)
  231. def handle_sigusr2(self):
  232. # log rotation signal - do the same as Zope 2.7/2.8...
  233. if self.options.config_logger is None or os.name not in ("posix", "nt"):
  234. log("received SIGUSR2, but it was not handled!",
  235. level=logging.WARNING)
  236. return
  237. loggers = [self.options.config_logger]
  238. if os.name == "posix":
  239. for l in loggers:
  240. l.reopen()
  241. log("Log files reopened successfully", level=logging.INFO)
  242. else: # nt - same rotation code as in Zope's Signals/Signals.py
  243. for l in loggers:
  244. for f in l.handler_factories:
  245. handler = f()
  246. if hasattr(handler, 'rotate') and callable(handler.rotate):
  247. handler.rotate()
  248. log("Log files rotation complete", level=logging.INFO)
  249. def _get_pidfile(self):
  250. pidfile = self.options.pid_file
  251. # 'pidfile' is marked as not required.
  252. if not pidfile:
  253. # Try to find a reasonable location if the pidfile is not
  254. # set. If we are running in a Zope environment, we can
  255. # safely assume INSTANCE_HOME.
  256. instance_home = os.environ.get("INSTANCE_HOME")
  257. if not instance_home:
  258. # If all our attempts failed, just log a message and
  259. # proceed.
  260. logger.debug("'pidfile' option not set, and 'INSTANCE_HOME' "
  261. "environment variable could not be found. "
  262. "Cannot guess pidfile location.")
  263. return
  264. self.options.pid_file = os.path.join(instance_home,
  265. "var", "ZEO.pid")
  266. def make_pidfile(self):
  267. if not self.options.read_only:
  268. self._get_pidfile()
  269. pidfile = self.options.pid_file
  270. if pidfile is None:
  271. return
  272. pid = os.getpid()
  273. try:
  274. if os.path.exists(pidfile):
  275. os.unlink(pidfile)
  276. f = open(pidfile, 'w')
  277. print(pid, file=f)
  278. f.close()
  279. log("created PID file '%s'" % pidfile)
  280. except IOError:
  281. logger.error("PID file '%s' cannot be opened" % pidfile)
  282. def remove_pidfile(self):
  283. if not self.options.read_only:
  284. pidfile = self.options.pid_file
  285. if pidfile is None:
  286. return
  287. try:
  288. if os.path.exists(pidfile):
  289. os.unlink(pidfile)
  290. log("removed PID file '%s'" % pidfile)
  291. except IOError:
  292. logger.error("PID file '%s' could not be removed" % pidfile)
  293. def create_server(storages, options):
  294. from .StorageServer import StorageServer
  295. return StorageServer(
  296. options.address,
  297. storages,
  298. read_only = options.read_only,
  299. client_conflict_resolution=options.client_conflict_resolution,
  300. msgpack=(options.msgpack if isinstance(options.msgpack, bool)
  301. else os.environ.get('ZEO_MSGPACK')),
  302. invalidation_queue_size = options.invalidation_queue_size,
  303. invalidation_age = options.invalidation_age,
  304. transaction_timeout = options.transaction_timeout,
  305. ssl = options.ssl,
  306. )
  307. # Signal names
  308. signames = None
  309. def signame(sig):
  310. """Return a symbolic name for a signal.
  311. Return "signal NNN" if there is no corresponding SIG name in the
  312. signal module.
  313. """
  314. if signames is None:
  315. init_signames()
  316. return signames.get(sig) or "signal %d" % sig
  317. def init_signames():
  318. global signames
  319. signames = {}
  320. for name, sig in signal.__dict__.items():
  321. k_startswith = getattr(name, "startswith", None)
  322. if k_startswith is None:
  323. continue
  324. if k_startswith("SIG") and not k_startswith("SIG_"):
  325. signames[sig] = name
  326. # Main program
  327. def main(args=None):
  328. options = ZEOOptions()
  329. options.realize(args)
  330. s = ZEOServer(options)
  331. s.main()
  332. def run(args):
  333. options = ZEOOptions()
  334. options.realize(args)
  335. s = ZEOServer(options)
  336. s.run()
  337. if __name__ == "__main__":
  338. main()